|
|
|
|
|
|
|
one and three can be any legal C++ statement, but statement two must be an expressiona C++ statement that returns a value. Listing 8.9 demonstrates the for loop. |
|
|
|
|
|
|
|
|
LISTING 8.9 DEMONSTRATING THEfor LOOP |
|
|
|
 |
|
|
|
|
1: // Listing 8.9
2: // Looping with for
3:
4: #include <iostream.h>
5:
6: int main()
7: {
8: int counter;
9: for (counter = 0; counter < 5; counter++)
10: cout < Looping! ;
11:
12: cout < \nCounter: < counter < .\n;
13: return 0;
14: } |
|
|
|
|
|
|
|
|
Looping! Looping! Looping! Looping! Looping!
counter: 5. |
|
|
|
|
|
|
|
|
Analysis: The for statement on line 9 combines the initialization of counter, the test that counter is less than 5, and the increment of counter all into one line. The body of the for statement is on line 10. Of course, a block could be used here as well. |
|
|
|
|
|
|
|
|
for statements are powerful and flexible. The three independent statements (initialization, test, and action) lend themselves to a number of variations. |
|
|
|
|
|
|
|
|
A for loop works in the following sequence: |
|
|
|
|
|
|
|
|
1. Performs the operations in the initialization. |
|
|
|
|
|
|
|
|
2. Evaluates the condition. |
|
|
|
|
|
|
|
|
3. If the condition is true, executes the action statement and the loop. |
|
|
|
|
|
|
|
|
After each time through the loop, it repeats steps 2 and 3. |
|
|
|
|
|
|
|
|
Multiple Initialization and Increments |
|
|
|
|
|
|
|
|
It is not uncommon to initialize more than one variable, to test a compound logical expression, and to execute more than one statement. The initialization and action statements can be replaced by multiple C++ statements, each separated by a comma. Listing 8.10 demonstrates the initialization and incrementing of two variables. |
|
|
|
|
|