< previous page page_124 next page >

Page 124
LISTING 8.11 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
10:        for ( ; counter < 5; )
11:        {
12:           counter++;
13:           cout < Looping!  ;
14:        }
15:
16:        cout < \nCounter:  < counter < .\n;
17:        return 0;
18:   }

Output:
 Looping!  Looping!  Looping!  Looping!  Looping!
counter: 5.
Analysis: You might recognize this as exactly like the while loop illustrated previously. On line 8, the counter variable is initialized. The for statement on line 10 does not initialize any values, but it does include a test for counter < 5. There is no increment statement, so this loop behaves exactly as if it had been written like this:
while (counter < 5)
Once again, C++ gives you a number of ways to accomplish the same thing. No experienced C++ programmer would use a for loop in this way, but it does illustrate the flexibility of the for statement. In fact, it is possible, using break and continue, to create a for loop with none of the three statements. Listing 8.12 illustrates how.
LISTING 8.12 ILLUSTRATING AN EMPTYfor LOOP STATEMENT

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:     //Listing 8.12 illustrating
2:     //empty for loop statement
3:
4:     #include <iostream.h>
5:
6:     int main()
7:     {
8:         int counter=0;       // initialization
9:         int max;
10:        cout < How many hellos?;
11:        cin >> max;
12:        for (;;)        // a for loop that doesn't end
13:        {
14:           if (counter < max)     // test
15:           {
16:            cout < Hello!\n;
17:            counter++;          // increment
18:           }
19:           else
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_124 next page >

If you like this book, buy it!