Loading lessons...
Nested Loops
Nested Loops
A nested loop is a loop inside another loop. The inner loop runs completely for every single pass of the outer loop.
The shape
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// inner body
}
}
For each trip of the outer loop, the inner loop does its entire count from scratch.
A times table
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << i * j << " ";
}
cout << endl;
}
return 0;
}
This prints a 3 by 3 grid of products. The inner loop lays out one row of numbers, then the outer loop moves to the next row.
Counting total runs
If the outer loop runs 3 times and the inner loop runs 3 times, the inner body runs 3 times 3 = 9 times in total. That is how you build grids and tables.
TL;DR
- A nested loop is a loop placed inside the body of another loop.
- The inner loop restarts at the start of every pass of the outer one.
- Total inner runs = outer count times inner count.
- Nested loops are ideal for grids and multiplication tables.