← Back to course

Nested Loops

You’ll be able to

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.

Total inner executions (fixed bounds)
outer passes × inner passes = total inner-body runs
When the inner bound depends on the outer variable, add up the per-pass counts instead of multiplying.
Worked example

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. 1.i = 1: inner loop runs for j = 1, printing 1 star, then a newline.
  2. 2.i = 2: inner loop runs for j = 1, 2, printing 2 stars, then a newline.
  3. 3.i = 3: inner loop runs for j = 1, 2, 3, printing 3 stars, then a newline.
  4. 4.Total stars printed: 1 + 2 + 3 = 6.
Answer: Six stars are printed, forming a triangle of rows 1, 2, and 3 stars long.
Checkpoint

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);`

Tip

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.

Checkpoint

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(); }`

On the exam

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