Loading lessons...
Nested Loops
Nested Loops
Put a loop inside a loop, and you get a nested loop - the inner loop runs fully for each step of the outer one.
The pattern
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
printf("i=%d j=%d\n", i, j);
}
}
Output:
i=1 j=1
i=1 j=2
i=1 j=3
i=2 j=1
i=2 j=2
i=2 j=3
How it runs
- The outer loop moves slowly: i = 1, then i = 2.
- For each outer step, the inner loop completes fully.
Total runs
Outer rounds (2) times inner rounds (3) = 6 total prints. Multiply to predict the count.
Real uses
- Printing tables, grids, and matrices.
- Comparing pairs of items.
- Many array patterns.
TL;DR
- Nested = inner loop repeats fully inside each outer step.
- Total runs = outer count x inner count.
- Great for grids and tables.
- Mind the braces and indentation.