< Previous | Contents | Next >

Nesting for Loops

You can nest for loops by putting one inside the other. Thats what I did in the following section of code, which counts out the elements of a grid. The outer loop, which begins:

for (int i = 0; i < ROWS; ++i)

simply executes its loop body ROWS (five) times. But it just so happens that theres another for loop inside this loop, which begins:

for (int j = 0; j < COLUMNS; ++j)

As a result, the inner loop executes in full for each iteration of the outer loop. In this case, that means the inner loop executes COLUMNS (three) times, for the ROWS (five) times the outer loop iterates, for a total of 15 times. Specifically, heres what happens:

1. The outer for loop declares i and initializes it to 0. Since i is less than

ROWS (5), the program enters the outer loops body.

2. The inner loop declares j and initializes it to 0. Since j is less than COLUMNS (3), the program enters its loop body, sending the values of i and j to cout, which displays 0, 0.

3. The program reaches the end of the body of the inner loop and increments j to 1. Since j is still less than COLUMNS (3), the program executes the inner loops body again, displaying 0, 1.

4. The program reaches the end of the inner loops body and increments j to 2. Since j is still less than COLUMNS (3), the program executes the inner loops body again, displaying 0, 2.

5. The program reaches the end of the inner loops body and increments j to 3. This time, however, j is not less than COLUMNS (3) and the inner loop ends.

6. The program finishes the first iteration of the outer loop by sending endl

to cout, ending the first row.

7. The program reaches the end of the outer loops body and increments i to 1. Since i is less than ROWS (5), the program enters the outer loops body again.

Understanding Objects 87


8. The program reaches the inner loop, which starts from the beginning once again, by declaring and initializing j to 0. The program goes through the process I described in Steps 2 through 7, displaying the sec- ond row of the grid. This process continues until all five rows have been displayed.

Again, the important thing to remember is that the inner loop is executed in full for each iteration of the outer loop.