Chapter 10. Looping for the Fun of It
In This Chapter
Introducing the
forloopReviewing an example ForFactorial program
Using the comma operator to get more done in a single
forloop
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
incrementvariable. This generally occurs immediately before thewhile.The test expression: The expression within the
whileloop that will cause the program to either execute the loop or exit and continue on. This always occurs within the parentheses following the keywordwhile.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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access