Chapter 1 by JNg02jTU

VIEWS: 9 PAGES: 12

									      Chapter 7
LOOPING OPERATIONS:
     ITERATION
Chapter 7

• The Flow of the while Loop

                        test          f alse
                                               . . .
   while
                     expression




                               true




                      loop body
Chapter 7

• while Loop Syntax
   while (test expression)
   {
     statement 1;
     statement 2;
            •

           statement n;
    } //END WHILE
Chapter 7

• DebuggingTip
  Remember, an infinite loop is the result of a
  logical error in your program. The compiler
  will not detect an infinite loop condition.
  For this reason, you should always desk-
  check your loop structures very closely
  prior to coding and execution. A little time
  desk-checking will save you a lot of time at
  the keyboard.
Chapter 7

• The Flow of the do/while Loop

  do                 loop body




                       while




             true         test    f alse
                        test               . . .
                     expression
Chapter 7
• do/while Loop Syntax
 do
 {
       statement 1;
           •
       statement n;
 } //END DO/WHILE
 while (test expression);
 Chapter 7
• The Flow of the
  for Loop
                                    test         f alse
            initialize     . . .                          . . .
 for                           expression on
          counter v alue         counter



                                        true




                                loop body




                           increment/decrement
                                 counter
  Chapter 7
• for Loop Syntax
  for (int counter = initial value; counter test;
                        increment or decrement
   counter)
   {
      statement 1;
      statement 2;
          •

           statement n;
    } //END FOR
Chapter 7

• Tips
  – Never change the for loop counter within the
    body of the loop.
  – Do not place a semicolon at the end of the first
    line of the for statement unless you purposely
    want to create a time delay.
Chapter 7
• The continue Statement
  When a continue statement is executed
  within a loop, only the current iteration is
  terminated and loop execution “continues”
  to the next iteration.
Chapter 7

• The break Statement
  When a break statement is executed within
  a loop, the loop “breaks” and all loop
  iterations are terminated. Execution then
  passes to the next sequential statement after
  the loop.
Chapter 7
   Use while whenever there is a possibility
    that the loop statements will not need to be
    executed.
   Use do/while when the loop statements
    must be executed at least once.
• Use for when it can be predetermined
  exactly how many times the loop statements
  must be executed.

								
To top