Nested Loops
You can put a loop inside another loop. These are called nested loops. They are useful for anything with rows and columns. The outer loop goes through the rows, and the inner loop goes through the columns of one row.
This program prints a small multiplication table:
#include <iostream>
using namespace std;
int main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
cout << row * col << " ";
}
cout << "\n";
}
return 0;
}
Output:
1 2 3
2 4 6
3 6 9
For each round of the outer loop, the inner loop runs completely, from start to end. While row is 1, col goes 1, 2, 3. Only then does row become 2, and the inner loop starts again from 1.
row | col goes | Printed |
|---|---|---|
| 1 | 1, 2, 3 | 1 2 3 |
| 2 | 1, 2, 3 | 2 4 6 |
| 3 | 1, 2, 3 | 3 6 9 |
So the innermost line ran 3 × 3 = 9 times in total.
The counters are named row and col here, not i and j. With two loops it is easy to mix up the counters, and clear names help you avoid that.
Where a line goes matters
Look at cout << "\n"; in the program above. It is inside the outer loop but after the inner loop, so it runs once per row. That is why each row is on its own line. Move it outside both loops, and it runs only once, at the very end:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
cout << row * col << " ";
}
}
cout << "\n";
Output:
1 2 3 2 4 6 3 6 9
Now all nine numbers are on one line. When a nested loop prints the wrong shape, check where each line sits: inside the inner loop (once per cell), inside only the outer loop (once per row), or outside both (once).
The inner loop does not have to run the same number of times in every row. It can use the outer counter, row. Here the inner loop starts at row, so each row is shorter than the one before:
for (int row = 1; row <= 3; row++) {
for (int col = row; col <= 3; col++) {
cout << col << " ";
}
cout << "\n";
}
Output:
1 2 3
2 3
3
In the exercise, use this idea to print a triangle of stars, one star longer in each row.