19.2.3. Iteration

[ fromfile: controlstructures.xml id: iteration ]

C++ provides three iteration structures.

  1. while loop:

    while ( loopCondition ) { 
       loopBody
    }
    1. Evaluate loopCondition first.

    2. Execute loopBody repeatedly until loopCondition is false.

  2. do..while loop:

    do { 
       loopBody 
    } while ( loopCondition ) ;
    1. Execute loopBody first.

    2. Evaluate loopCondition.

    3. Execute loopBody repeatedly until loopCondition is false.

  3. for loop:

    for ( initStatement; loopCondition; incrStmt ) {
       loopBody
    }
    1. Execute initStatement first.

    2. Execute loopBody repeatedly until loopCondition is false.

    3. After each execution of loopBody, execute incrStmt.

With each of these iteration structures, the loopBody code gets repeated as long as loopCondition evaluates to true. The do loop differs from the other two in that its loopCondition gets checked at the bottom of the loop, so its loopBody is always executed at least once.

A common programming error is to place a semicolon after the while.

while (notFinished()) ;
    doSomething();

The first semicolon terminates the while statement entirely and produces a loop with an empty loopBody. Even though doSomething() is indented, it does not get executed inside the loop. The loopBody is responsible for changing the loopCondition. If notFinished() is initially true then the empty loopBody causes an infinite loop. If notFinished() is initially false then the loop terminates immediately and doSomething() gets executed exactly once.

C++ provides break and continue for finer control over code executed inside loops:

while ( moreWorkToDo ) {
    statement1;
    if ( specialCase ) continue;
    statement2;
    if ( noMoreInput ) break;
    statement3; 
// continue jumps here
}  
// break jumps here 

break jumps out of the current control structure, whether it is a switch, for, while, or do..while.

continue operates only inside loops. It skips the remaining statements in the current iteration and checks the moreWorkToDo condition. Example 19.2 shows how you might use continue and break.

Example 19.2. src/continue/continue-demo.cpp

#include <QTextStream>
#include <cmath>

int main() {
   QTextStream cout(stdout);
   QTextStream cin(stdin);
   int num(0), root(0), count;
   cout << "How many perfect squares? "<< flush;
   cin >> count;
   for(num = 0;; ++num) {
      root = sqrt(num);  1
      if(root * root != num) 
         continue;
      cout << num << endl;
      --count;
      if(count == 0) 
         break;
   }
}

1

Convert sqrt to int.