Chapter 10. Looping for the Fun of It

In This Chapter

  • Introducing the for loop

  • Reviewing an example ForFactorial program

  • Using the comma operator to get more done in a single for loop

The most basic of all control structures is the while loop, which is the topic of Chapter 9. This chapter introduces you its sibling, the for 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.

The for Parts of Every Loop

If you look again at the examples in Chapter 9, you'll notice that most loops have four essential parts. (This feels like breaking down a golf swing into its constituent 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 ...

Get Beginning Programming with C++ For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.