< previous page page_126 next page >

Page 126
Analysis: The for loop on line 8 includes three statements. The initialization statement establishes the counter i and initializes it to 0. The condition statement tests for i<5, and the action statement prints the value in i and increments it.
There is nothing left to do in the body of the for loop, so the null statement (;) is used. Note that this is not a well-designed for loop; the action statement is doing far too much. This would be better rewritten as
8:          for (int i = 0; i<5; i++)
9:               cout < i:  < i < endl;
Although both do exactly the same thing, this example is easier to understand.
Nested Loops.
Loops can be nested, with one loop sitting in the body of another. The inner loop will be executed in full for every execution of the outer loop. Listing 8.14 illustrates writing marks into a matrix using nested for loops.
LISTING 8.14 NESTEDfor LOOPS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:   //Listing 8.14
2:   //Illustrates nested for loops
3:
4:   #include <iostream.h>
5:
6:   int main()
7:   {
8:       int rows, columns;
9:       char theChar;
10:      cout < How many rows? ;
11:      cin >> rows;
12:      cout < How many columns? ;
13:      cin >> columns;
14:      cout < What character? ;
15:      cin >> theChar;
16:      for (int i = 0; i<rows; i++)
17:      {
18:          for (int j = 0; j<columns; j++)
19:              cout < theChar;
20:          cout < \n;
21:      }
22:      return 0;
23:  }

Output:
How many rows? 4
How many columns?  12

 
< previous page page_126 next page >

If you like this book, buy it!