All lessons
LESSON 23/53Bigger Programs
Nested Loops
GOALPut a loop inside a loop to build rows and shapes.

Like clock hands: for every single step of the outer loop, the inner loop runs all the way round. Perfect for rows and columns.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
cout << "*";
}
cout << endl;
}
return 0;
}> what you see
* ** *** ****
//LINE BY LINE
Watch it run
row = 1. The inner loop starts and prints the first star.
How it actually runs
For each turn of the outer loop, the inner loop runs all the way through. So the total number of turns is the product.
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
cout << i << j << " ";
}
}> what you see
11 12 13 21 22 23
Two-dimensional arrays
Table-shaped data needs two indexes: the first is the row, the second is the column.
int grid[3][4]; // 3 мөр, 4 багана
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) {
cin >> grid[r][c];
}
}