< previous page page_123 next page >

Page 123
LISTING 8.10 DEMONSTRATING MULTIPLE STATEMENTS INfor LOOPS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:  //listing 8.10
2:  // demonstrates multiple statements in
3:  // for loops
4:
5:  #include <iostream.h>
6:
7:  int main()
8:  {
9:      for (int i=0, j=0; i<3; i++, j++)
10:          cout < i:  < i <  j:  < j < endl;
11:     return 0;
12: }

Output:
i: 0  j: 0
i: 1  j: 1
i: 2  j: 2
Analysis: On line 9, two variables, i and j, are each initialized with the value 0. The test (i<3) is evaluated, and because it is true, the body of the for statement is executed and the values are printed. Finally, the third clause in the for statement is executed, and i and j are incremented.
After line 10 completes, the condition is evaluated again, and if it remains true the actions are repeated (i and j are again incremented), and the body of loop is executed again. This continues until the test fails, in which case the action statement is not executed, and control falls out of the loop.
null Statements in for Loops
Any or all of the statements in a for loop can be null. To accomplish this, use the semicolon to mark where the statement would have been. To create a for loop that acts exactly like a while loop, leave out the first and third statement. Listing 8.11 illustrates this idea.
LISTING 8.11null STATEMENTS INfor LOOPS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:    // Listing 8.11
2:    // For loops with null statements
3:
4:    #include <iostream.h>
5:
6:    int main()
7:    {
8:        int counter = 0;
9:
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_123 next page >

If you like this book, buy it!