Sams Teach Yourself C++ in 21 Days

(singke) #1
LISTING7.8 whileReexamined
1: // Listing 7.8
2: // Looping with while
3:
4: #include <iostream>
5:
6: int main()
7: {
8: int counter = 0;
9:
10: while(counter < 5)
11: {
12: counter++;
13: std::cout << “Looping! “;
14: }
15:
16: std::cout << “\nCounter: “ << counter << std::endl;
17: return 0;
18: }

Looping! Looping! Looping! Looping! Looping!
Counter: 5.
In this listing, you can see that three steps are occurring. First, the starting condi-
tion is set on line 8:counteris initialized to 0. On line 10, the test of the condi-
tion occurs when counteris tested to see if it is less than 5. Finally, the countervariable
is incremented on line 12. This loop prints a simple message at line 13. As you can imag-
ine, more important work could be done for each increment of the counter.
A forloop combines the three steps into one statement. The three steps are initializing,
testing, and incrementing. A forstatement consists of the keyword forfollowed by a
pair of parentheses. Within the parentheses are three statements separated by semicolons:
for( initialization; test; action)
{
...
}
The first expression,initialization, is the starting conditions or initialization. Any
legal C++ statement can be put here, but typically this is used to create and initialize a
counting variable. The second expression,test, is the test, and any legal C++ expression
can be used here. This test serves the same role as the condition in the whileloop. The
third expression,action, is the action that will take place. This action is typically the
increment or decrement of a value, though any legal C++ statement can be put here.
Listing 7.9 demonstrates a forloop by rewriting Listing 7.8.

OUTPUT


188 Day 7


ANALYSIS
Free download pdf