By Stephen R. Davis

The most basic of all control structures in C++ is the while loop. Though not quite as flexible, the for loop is actually the more popular of the two — it has a certain elegance that is hard to ignore. You’ll notice that most loops have four essential parts.

  • The setup: Usually the setup involves declaring and initializing an increment variable. This generally occurs immediately before the while.

  • The test expression: The expression within the while loop that will cause the program to either execute the loop or exit and continue on. This always occurs within the parentheses following the keyword while.

  • The body: This is the code within the braces.

  • The increment: This is where the increment variable is incremented. This usually occurs at the end of the body.

In the case of the Factorial program, the four parts looked like this:

int nValue = 1;             // the setup
while (nValue <= nTarget)   // the test expression
{                           // the body
    cout << nAccumulator << " * "
         << nValue << " equals ";
    nAccumulator = nAccumulator * nValue;
    cout << nAccumulator << endl;
    nValue++;               // the increment

The for loop incorporates these four parts into a single structure using the keyword for:

for(setup; test expression; increment)

The flow is shown graphically here:


  1. As the CPU comes innocently upon the for keyword, control is diverted to the setup clause.

  2. Once the setup has been performed, control moves over to the test expression.

  3. (a) If the test expression is true, control passes to the body of the for loop.

    (b) If the test expression is false, control passes to the next statement after the closed brace.

  4. Once control has passed through the body of the loop, the CPU is forced to perform a U-turn back up to the increment section of the loop.

  5. That done, control returns to the test expression and back to Step 3.

This for loop is completely equivalent to the following while loop:

while(test expression)