Skip to main content

Section 8.5 The for Statement

The loops we have written so far have three parts in common. They initialize a loop control variable before the loop, they have a condition that depends on that variable, and they do something inside the loop to update that variable:
Listing 8.5.1.
int i = 0;              //initialize
while (i < 5) {         //test
    cout << i << endl;
    i++;                //update
}
The for loop, is a way to expresses those three parts more concisely. The for loop has three components in parentheses, separated by semicolons: the initializer, the condition, and the update:
for (initializer; test; update) {
    body
}
  1. The initializer runs once at the very beginning of the loop. It is equivalent to the line before the while statement.
  2. The condition is checked each time through the loop. If it is false, the loop ends. Otherwise, the body of the loop is executed (again).
  3. At the end of each iteration, after the body, the update runs, and we go back to the start. (You can imagine that the update automatically gets inserted right before the } at the end of the body.)
For example, we can rewrite the 1-5 loop this way:
Listing 8.5.2.
The for loop is often easier to read because it puts all the loop-related statements at the top of the loop. Looking at the statement in that loop, I can tell that it start from 1, goes up to 5, and counts by 1. In the equivalent while loop, the update might be separated from the test by quite a bit of code, making it harder to see at a glance see what the loop is doing.
Here is the 2, 4, 6, 8 loop written as a while and as a for side by side for comparison:
int i = 2;
while (i <= 8) {
    cout << i;
    i += 2;
}
cout << "Who do we appreciate?";
for (int i = 2; i <= 8; i += 2) {
    cout << i << endl;
}
cout << "Who do we appreciate?";
There is another difference between for loops and while loops: if you declare a variable in the initializer, it exists only inside the for loop. For example, this program has a syntax error - i no longer is in scope once we leave the loop:
Listing 8.5.3.
This can actually be an advantage. If you want to keep reusing the same name for your loop counters, you can do so with a for loop. Each time a loop ends, the variables created in the initializer are no longer in scope.
For loops and while loops are interchangeable. There is no loop you can write with one that you can’t write with the other. So you should pick the one that makes your code easiest to read. For a counting loop, a for loop is often the correct choice. For other kinds of loops (like the sentinel loop we are about to learn about), a while loop may allow for a clearer expression of your intent.
A final note about for loops: It is possible for the initialize or update to be empty:
Listing 8.5.4.
// empty initialize
for ( ; i < 5; i++) { ...

// empty update
for (int i = 0; i < 5;  ) { ...
In the first one, i would already have to exist. In the second example, we would need to update i inside the loop body to avoid an infinite loop. Although these structures are legal, they are usually a sign that you are using a for loop when a while loop would be the better way to express what you want to do.

Checkpoint 8.5.1.

On the last day of every year, we count down the seconds before the new year arrives. Write the function newYearCountdown, which prints out a countdown from 10 and then prints out β€œHappy New Year!”.
You have attempted of activities on this page.