How do nested loops work, and how do you count the total iterations of an inner loop inside an outer loop?
Topic 4.4 Nested Iteration: write and trace nested loops, where an inner loop runs in full on each pass of an outer loop, and count the total number of inner-loop iterations.
A focused answer to AP CSA Topic 4.4, covering nested loops, how the inner loop completes fully on each outer pass, counting total iterations (including triangular patterns where the inner bound depends on the outer variable), and tracing nested output, with a fully worked example.
Reviewed by: AI editorial process; not yet individually human-reviewed
Have a quick question? Jump to the Q&A page
Jump to a section
What this topic is asking
The College Board (Topic 4.4) wants you to write and trace nested loops: a loop placed inside the body of another loop. The crucial idea is that the inner loop runs to completion on every single pass of the outer loop. You must be able to count the total number of inner-loop iterations, including the common case where the inner loop's bound depends on the outer loop's control variable (producing a triangular count).
How nested loops execute
for (int i = 1; i <= 2; i++) { // outer
for (int j = 1; j <= 3; j++) { // inner
System.out.println(i + " " + j);
}
}
The code above prints six lines: for i = 1 the inner loop prints j = 1, 2, 3; then i becomes 2 and the inner loop again prints j = 1, 2, 3. The inner control variable resets at the top of each outer pass.
Counting total iterations
Two common cases:
- Rectangular:
for i in 1..m { for j in 1..k { ... } }runsm * ktimes. - Triangular:
for i in 1..n { for j in 1..i { ... } }runs1 + 2 + ... + ntimes, which equalsn * (n + 1) / 2.
Recognizing which case you have is the key exam skill. A bound of j <= i (or j < i) signals a triangular count; a bound of j <= n (independent of i) signals a rectangular one. The quickest test is to look at the inner loop's condition and ask whether it mentions the outer control variable: if it does, the inner length changes each outer pass and you must add the per-pass counts; if it does not, the inner length is constant and you multiply. For three levels of nesting the same logic applies, working from the innermost loop outward.
Tracing nested output
To trace, fix the outer variable, run the inner loop completely while listing its output, then advance the outer variable and repeat. Keep a clear record of both control variables at each step.
Try this
Q1. How many times does the body run in for i in 1..4 { for j in 1..5 { ... } }? [1 point]
- Cue.
4 * 5 = 20- both bounds are fixed, so it is rectangular.
Q2. Explain why for i in 1..n { for j in 1..i { ... } } does not run n * n times. [2 points]
- Cue. The inner bound
j <= ichanges each outer pass, so the inner loop runs 1, 2, ..., n times; the total is the sum1 + 2 + ... + n, which isn(n+1)/2, notn * n.
Exam-style practice questions
Practice questions written in the style of College Board exam questions on this dot point, with worked answer explainers. The year tag is the paper they imitate, not the source.
AP 2021 (style)1 marksMultiple choice. How many times does the statement `System.out.println("*")` execute?
```java
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.println("*");
}
}
```
(A) `6`
(B) `9`
(C) `3`
(D) `4`
(E) `12`
Show worked answer →
The answer is (A).
The inner loop runs i times for each value of i, because its bound is j <= i. When i = 1, the inner loop runs 1 time; when i = 2, 2 times; when i = 3, 3 times. The total is 1 + 2 + 3 = 6. (B) wrongly assumes the inner loop always runs 3 times (which would be the case only if the bound were j <= 3); (C) counts only the outer loop.
Markers reward noticing that the inner bound depends on the outer variable, giving a triangular count 1 + 2 + 3, not 3 * 3.
AP 2020 (style)4 marksFree response (code writing). A positive `int` variable `n` is given. Write a code segment using nested loops that prints `n` rows, where row number `r` (from 1 to n) contains `r` hash characters with no spaces, each row on its own line. For example, if `n` is 3, the output is "#", then "##", then "###".
Show worked answer →
A 4-point question testing a triangular nested-loop pattern.
for (int r = 1; r <= n; r++) {
String line = "";
for (int c = 1; c <= r; c++) {
line = line + "#";
}
System.out.println(line);
}
Point 1: the outer loop runs r from 1 to n, one pass per row. Point 2: the inner loop runs c from 1 to r, so row r gets r hashes. Point 3: building the line with accumulation, resetting line to "" at the start of each outer pass. Point 4: printing each row on its own line. Resetting line outside the outer loop, or using c <= n, would produce the wrong shape.
Related dot points
- Topic 4.2 for Loops: use a for loop, whose header combines initialisation, a boolean condition and an update, to repeat a block a controlled number of times, and convert between for and while loops.
A focused answer to AP CSA Topic 4.2, covering for-loop header syntax (init; condition; update), the order in which the three parts run, counting iterations, equivalence with while loops, common patterns, and tracing, with a fully worked example.
- Topic 4.1 while Loops: use a while loop to repeat a block of statements while a boolean condition remains true, with correct initialisation, condition and update to avoid infinite or off-by-one loops.
A focused answer to AP CSA Topic 4.1, covering while loop syntax, the initialise/test/update pattern, why each loop control variable must change, infinite loops and off-by-one errors, and how to trace iterations, with a fully worked example.
- Topic 4.5 Informal Code Analysis: determine the number of times a statement executes in a loop or nested loop by counting iterations, without using formal big-O notation.
A focused answer to AP CSA Topic 4.5, covering how to count statement executions in single and nested loops, the effect of step size and start/end bounds, conditional statements inside loops, and triangular versus rectangular counts, with a fully worked counting example.
- Topic 4.3 Developing Algorithms Using Strings: traverse a String with a loop using length, substring and indexOf to implement standard algorithms such as counting characters, searching for a pattern and building a new String.
A focused answer to AP CSA Topic 4.3, covering String traversal with a for loop, extracting one character with substring, the standard counting, searching and accumulation patterns, the half-open index range, and bounds safety, with a fully worked example.
- Topic 3.3 if-else Statements: use a two-way if-else statement so that exactly one of two code blocks runs depending on whether the boolean condition is true or false.
A focused answer to AP CSA Topic 3.3, covering two-way selection with if-else, the guarantee that exactly one branch runs, how the else attaches to the nearest if, nested if-else, and how to trace each branch, with a fully worked example.
Sources & how we know this
- AP Computer Science A Course and Exam Description — College Board (2025)