AP Computer Science A · Selection and iteration
Nested iteration
1Loops inside loops
A nested loop has one loop inside another. For each iteration of the outer loop, the inner loop runs completely.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print("*");
}
System.out.println();
}
This prints 3 rows of 4 stars. The inner body runs $3 \times 4 = 12$ times.
Check yourself
An outer loop runs 5 times and an inner loop runs 6 times per outer iteration. The inner body runs:
Show the answer
30 times
5 × 6.
2Inner loops that depend on the outer variable
The inner loop's bounds can use the outer variable, producing triangular patterns:
for (int r = 1; r <= 4; r++) {
for (int c = 1; c <= r; c++) {
System.out.print(c);
}
System.out.println();
}
Output:
- 1
- 12
- 123
- 1234
Total inner iterations: $1 + 2 + 3 + 4 = 10$. In general, $1 + 2 + \dots + n = \frac{n(n + 1)}{2}$.
When the inner loop depends on the outer variable, the work forms a triangle
Check yourself
How many times does the inner body run? for (int i = 0; i < 5; i++) for (int j = i; j < 5; j++)
Show the answer
15
5 + 4 + 3 + 2 + 1.
3Common nested-loop algorithms
- Comparing all pairs:
for (i...) for (j = i + 1; ...)checks every pair once, e.g. to find duplicates. - Grids and 2D arrays: row loop outside, column loop inside.
- Substrings: all substrings of length
kwith an inner loop over positions.
does a string contain a repeated letter?
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
if (s.substring(i, i + 1).equals(s.substring(j, j + 1))) {
return true;
}
}
}
return false;
Starting j at i + 1 avoids comparing a letter with itself and checking each pair twice.
Check yourself
Why does the inner loop start at j = i + 1 when checking pairs?
Show the answer
To avoid comparing an item with itself and repeating pairs
Each pair once.
4Efficiency and statement execution counts
Multiple-choice questions often ask how many times a statement executes.
- Independent loops of $n$ and $m$: $n \times m$.
- Inner loop depending on outer (triangular): about $\frac{n^2}{2}$.
- A loop that halves its variable runs about $\log_2 n$ times.
Nested loops over $n$ items take time proportional to $n^2$, so doubling $n$ roughly quadruples the work.
Check yourself
A nested loop with both loops running n times takes about how much longer if n doubles?
Show the answer
4 times as long
n² grows by 4.
5Going deeper: counting executions, patterns and comparing pairs
A nested loop runs its entire inner loop for each pass of the outer loop.
Counting how many times the inner body runs
- Independent bounds: multiply. Outer n times, inner m times: n × m.
- Inner bound depends on the outer variable: add up the passes. This is usually a triangular count.
Worked example (rectangle):
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 6; c++) {
count++;
}
}
4 × 6 = 24.
Worked example (triangle):
for (int i = 0; i < 5; i++) {
for (int j = 0; j < i; j++) {
count++;
}
}
- i = 0: inner runs 0 times.
- i = 1: 1. i = 2: 2. i = 3: 3. i = 4: 4.
- Total 0 + 1 + 2 + 3 + 4 = 10.
- In general
j < igives n(n − 1) ÷ 2, andj <= igives n(n + 1) ÷ 2.
Worked example (starting from i + 1):
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
count++;
}
}
For n = 5: 4 + 3 + 2 + 1 + 0 = 10. This pattern visits every pair of positions exactly once.
Printing patterns: the outer loop controls rows; the inner loop prints the characters within a row; println after the inner loop ends the row.
for (int row = 1; row <= 4; row++) {
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
System.out.println();
}
Output: a triangle with 1, 2, 3 and 4 stars.
Worked example (trace the output):
for (int i = 1; i <= 3; i++) {
for (int j = i; j <= 3; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}
- i = 1: j = 1, 2, 3: prints
1 2 3. - i = 2: j = 2, 3: prints
4 6. - i = 3: j = 3: prints
9.
Comparing every pair (for example, looking for duplicates):
boolean hasDuplicate = false;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
hasDuplicate = true;
}
}
}
Starting j at i + 1 avoids comparing an element with itself and avoids checking each pair twice.
Nested loops over strings: finding whether any character of one string appears in another, or counting substrings, uses the same structure with substring(i, i + 1).
Efficiency: a single loop over n items does about n steps; a pair of nested loops does about n². Doubling n quadruples the work. For n = 1000, that is a million inner-body executions.
Tracing advice
- Write down the outer variable; run the inner loop completely; only then advance the outer variable.
- The inner loop variable is re-initialized on every outer pass.
- Watch what belongs to which loop: a statement after the inner loop's closing brace runs once per outer pass.
Worked example (statement placement): how many lines are printed?
for (int a = 0; a < 3; a++) {
for (int b = 0; b < 2; b++) {
System.out.println("inner");
}
System.out.println("outer");
}
- "inner": 3 × 2 = 6.
- "outer": 3.
- Nine lines.
A loop inside a while: the same reasoning applies; count the outer passes first.
Break from the inner loop only: a return leaves the whole method; ending just the inner loop early needs its own condition.
Common mistakes
- Using the same variable for both loops.
- Multiplying when the inner bound depends on the outer variable.
- Putting
printlninside the inner loop, so every character lands on its own line. - Starting j at 0 when comparing pairs, so each element is compared with itself.
- Off-by-one in a triangular count (
<against<=).
Check yourself
How many times is the innermost statement executed in for (int i = 1; i <= 4; i++) for (int j = 1; j <= i; j++) count++;?
Show the answer
10
1 + 2 + 3 + 4.
6For top marks
- Trace nested loops with a table listing both loop variables.
- Count executions by summing the inner iterations for each outer value.
- Reset inner accumulators inside the outer loop if they belong to each row.
- Use
breaksparingly; returning from a method inside a nested loop is clearer.
printing a multiplication table needs the outer loop for rows and the inner for columns, printing r * c and a new line after each row.
Check yourself
What does this print? for (int i = 1; i <= 2; i++) for (int j = 1; j <= 3; j++) System.out.print(i * j + " ");
Show the answer
1 2 3 2 4 6
Inner loop runs fully each time.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera