AP® Computer Science A · Unit 2 · Topic 2.11

Drawing Patterns with Nested Loops

A nested loop prints patterns because the outer loop picks each row and the inner loop prints that row's contents from scratch, one pass per row.

Two loops working together build patterns because each one owns a different job. The outer loop counts rows: it runs once per line of output, and nothing inside it prints directly. The inner loop does the actual printing, running completely from start to finish during each single pass of the outer loop. When the inner loop finishes, the outer loop moves to its next value, and the inner loop starts over at its own beginning. That restart is the whole trick: the inner loop does not remember where it left off, so its bound can depend on the current value of the outer counter and produce a different amount of output each row.

For a right triangle where row i has i stars, the inner loop's bound is simply the outer counter: for (int i = 1; i ≤ 5; i++) runs the outer loop for rows 1 through 5, and inside it for (int j = 1; j ≤ i; j++) prints j from 1 to i, giving i stars that row. Row 1 prints 1 star, row 2 prints 2, up through row 5 printing 5, for a total of 1+2+3+4+5 = 15 stars, matching n(n+1)/2 with n = 5. A multiplication table instead fixes the inner bound at a constant, 5, instead of i, so every row has the same length but a different starting multiplier.

Flipping the triangle to point the other way means the row lengths still follow a pattern, but now row i needs n - i + 1 stars instead of i, so the inner bound changes from j ≤ i to j ≤ n - i + 1. This topic is where trace tables earn their keep: write i and j as columns, fill one row per inner-loop pass, and the table shows exactly when each loop resets versus continues, which is the same skill used to debug any nested loop later.

Key terms

outer loop
The loop that controls how many rows get printed, running once per row.
inner loop
The loop that runs completely during each single pass of the outer loop, producing one row's content.
loop bound
The condition, such as j ≤ i, that determines how many times a loop executes.
trace table
A table with one row per loop pass, tracking variable values to follow a loop's execution step by step.

Watch it explained

  1. How it worksHow does the inner loop's bound control the length of each printed row?
  2. Worked exampleTrace the output of a nested loop that prints a right triangle of 5 rows of stars.
  3. Worked exampleFind the loop bounds that print a multiplication table for 1 through 5.
  4. Going furtherWhat changes in the bounds when the triangle has to point the other way?

Check yourself

Your turn1 of 2
A nested loop prints a right triangle of stars with 15 rows, where row i (starting at row 1) contains exactly i stars. In total, how many stars get printed?

End of topic.