19.2.3. Iteration

[ fromfile: controlstructures.xml id: iteration ]

  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.

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

while (notFinished()) ;
    doSomething();

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.