|
|
|
|
|
|
|
When programming while loops, you'll often find yourself setting up a starting condition, testing to see if the condition is true, and incrementing or otherwise changing a variable each time through the loop. Listing 8.8 demonstrates this. |
|
|
|
|
|
|
|
|
LISTING 8.8while REEXAMINED |
|
|
|
 |
|
|
|
|
1: // Listing 8.8
2: // Looping with while
3:
4: #include <iostream.h>
5:
6: int main()
7: {
8: int counter = 0;
9:
10: while (counter < 5)
11: {
12: counter++;
13: cout < Looping! ;
14: }
15:
16: cout < \nCounter: < counter < .\n;
17: return 0;
18: } |
|
|
|
|
|
|
|
|
Looping! Looping! Looping! Looping! Looping!
counter: 5. |
|
|
|
|
|
|
|
|
Analysis: The condition is set on line 8: counter is initialized to 0. On line 10 counter is tested to see if it is less than 5. counter is incremented on line 12. On line 13, a simple message is printed, but you can imagine that more important work could be done for each increment of the counter. |
|
|
|
|
|
|
|
|
A for loop combines the three steps of initialization, test, and increment into one statement. A for statement consists of the keyword for followed by a pair of parentheses. Within the parentheses are three statements separated by semicolons. |
|
|
|
|
|
|
|
|
The first statement is the initialization. Any legal C++ statement can be put here, but typically this is used to create and initialize a counting variable. Statement two is the test, and any legal C++ expression can be used there. This serves the same role as the condition in the while loop. Statement three is the action. Typically a value is incremented or decremented, although any legal C++ statement can be put there. Note that statements |
|
|
|
|
|