CSCD-255
2015-01-22

Link back to 20 Jan for some unfinished business.


Loops in Two Flavors (Chapter 14)

Top-driven loops:  the logical expression at the top is evaluated, and if that is true, the body of the loop is entered, if it is false, the body of the loop is skipped and control passes to the program segment following the while loop..  When the body of the loop has been processed, control returns to the top, where the logical expression is again evaluated.   It is critical that the body of the loop change something that is involved in the logical expression, or you have to use a technique from a later chapter to get out of the loop.

   while (<logical expression>)
   {
      <body of the loop>
   }
   <program segment following>
   
Specimen:   TopLoop.txt   TopLoop.c   TopLoop.exe

Further specimen:  a counting loop that runs a specific number of times.
CountingLoop.txt   CountingLoop.c   CountingLoop.exe

Bottom-driven loop:  the loop starts with the reserved word "do" followed by a compound statement (code contained between curly brackets ("{" "}").  While it technically could be a single statement, for all practical purposes it never is.  (Remember that the loop must change something involved in the logical expression.)  The close bracket is followed by the reserved word while and a logical expression in parentheses and then followed by a semicolon.  In other words, the entire segment from the do until the close parenthesis on the while condition is one statement and so must be followed by a semicolon.

   do
   {
      <body of the loop>
   } while (<logical expression>);
   <program segment following>
The body of the loop is always executed at least once because the logical expression is at the end.  If the logical expression is true, the body of the loop is executed again.  If it is false, control passes to the program segment following the do-while loop.
Specimen:   BottomLoop.txt   BottomLoop.c   BottomLoop.exe