Nested Loops
- Trace a loop nested inside another loop
- Count the total number of times an inner body executes
- Handle an inner loop whose bound depends on the outer variable
A loop inside a loop
A nested loop places one loop inside another. For each single pass of the outer loop, the inner loop runs to completion. If the outer loop runs 3 times and the inner loop runs 2 times per outer pass, the inner body executes 3 × 2 = 6 times total. Nested loops are how you process grids, tables, and every pair of items.
Counting inner executions
When both bounds are fixed, multiply them: an outer loop of n passes around an inner loop of m passes runs the inner body n × m times. Tracking a counter that increments in the inner body is a reliable way to verify this — the final count equals the product.
When the inner bound depends on the outer
Often the inner loop’s limit depends on the outer variable, as in for (int j = 1; j <= i; j++). Then the number of inner passes grows each time: 1 pass when i = 1, 2 passes when i = 2, and so on. The total is the sum of those counts, not a simple product. This pattern draws triangular shapes and appears throughout array work.
How many stars print? for (int i = 1; i <= 3; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }
- 1.i = 1: inner loop runs for j = 1, printing 1 star, then a newline.
- 2.i = 2: inner loop runs for j = 1, 2, printing 2 stars, then a newline.
- 3.i = 3: inner loop runs for j = 1, 2, 3, printing 3 stars, then a newline.
- 4.Total stars printed: 1 + 2 + 3 = 6.
What does this print? `int count = 0;` then `for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { count++; } }` then `System.out.println(count);`
For fixed nested bounds, the inner body runs outer × inner times. Reach for this shortcut first, then trace only if a bound depends on the outer variable.
How many total `*` characters does this print? `for (int i = 1; i <= 3; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }`
When the inner bound is the outer variable (j <= i), do not multiply — add the per-row counts. A triangular pattern like 1 + 2 + 3 is the tell.
Answer the 2 checkpoints as you read.
Sign in to save your progress