A nested loop is a loop inside the body of another loop. The inner loop runs all of its passes (iterations) every time the outer loop runs once, so when neither bound changes, the inner body runs (outer passes) × (inner passes) times. When the inner bound uses the outer loop's variable, you count the inner passes for each outer pass and add them.
Quick check
How many times does the body of for (int k = 0; k < 5; k++) run?Show answerHide answer
Five times, with
kequal to 0, 1, 2, 3 and 4. Whenkreaches 5, the conditionk < 5is false and the loop stops.How many times does the body of for (int k = 3; k <= 7; k++) run?Show answerHide answer
Five times: 3, 4, 5, 6 and 7. A loop that counts up by 1 from
atobinclusive runsb - a + 1times.
Know these already? Jump to the practice questions
What you'll be able to do
- Explain why an inner loop runs in full on each outer pass.
- Calculate how many times a nested loop body runs, with fixed or dependent bounds.
- Predict the exact pattern a nested loop prints with
printandprintln. - Identify the header or line that makes a nested loop print the wrong pattern.
Key terms
Nested loop
A loop written inside the body of another loop.
- In plain English
- A loop within a loop.
- Don't write
- "The two loops take turns, one pass each."
Outer loop
The loop whose body contains the other loop.
- In plain English
- The loop on the outside, which usually picks the row.
- Don't write
- "The outer loop finishes before the inner loop starts."
Inner loop
The loop inside the outer loop's body. Its header runs again on every outer pass.
- In plain English
- The loop on the inside, which usually fills in one row.
- Don't write
- "The inner loop variable carries on from where it stopped last time."
How does an inner loop run inside an outer loop?
Each outer pass reaches the inner loop, which runs all of its iterations before that outer pass can end. On the next outer pass the inner header runs again, so j starts over.
for (int i = 1; i <= 2; i++)
{
for (int j = 1; j <= 3; j++)
{
System.out.println(i + " " + j);
}
}
| Line printed | i | j |
|---|---|---|
| 1st | 1 | 1 |
| 2nd | 1 | 2 |
| 3rd | 1 | 3 |
| 4th | 2 | 1 |
| 5th | 2 | 2 |
| 6th | 2 | 3 |
j changes on every line but i only after three, because the inner loop must finish before i++ runs. Loop syntax is not on the Java Quick Reference: Learn this.
Key idea
For each single pass of the outer loop, the inner loop runs from its first value to its last.
Check yourself
Show answerHide answer
i is 2 and j is 2. Lines 1 to 3 use i = 1, so lines 4, 5 and 6 use i = 2 with j = 1, 2 and 3.
How many times does the inner body run when the bounds are fixed?
Count each loop on its own, then multiply. A loop for (int k = a; k < b; k++) runs b - a times; with <= in place of < it runs b - a + 1 times.
int count = 0;
for (int r = 0; r < 4; r++)
{
for (int c = 2; c <= 6; c++)
{
count++;
}
}
The outer loop runs 4 times (r from 0 to 3), and on every outer pass the inner loop runs 6 − 2 + 1 = 5 times. So count++ runs 4 × 5 = 20 times. Multiplying works only because the inner header never mentions r, so every outer pass gets the same inner count.
Check yourself
Show answerHide answer
21 times: 3 outer passes × 7 inner passes.
What if the inner bound depends on the outer variable?
When the inner header uses the outer variable, each outer pass can run a different number of inner passes. You can't multiply, so list the inner count for each outer value and add.
int count = 0;
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= i; j++)
{
count++;
}
}
For i = 1, 2, 3 and 4 the inner loop runs 1, 2, 3 and 4 times, because j goes from 1 up to i. The total is 1 + 2 + 3 + 4 = 10, so count ends at 10. A shortcut for sums like this is 1 + 2 + … + n = n(n + 1) / 2, which gives 4 × 5 / 2 = 10. No formula sheet gives it: Learn this.
Key idea
With a dependent inner bound, write the inner count for each outer value and add them; don't multiply.
Check yourself
Show answerHide answer
6 times. The inner counts become 0, 1, 2 and 3 for i = 1 to 4, and 0 + 1 + 2 + 3 = 6.
How do you predict a printed pattern?
System.out.print leaves the line open; System.out.println ends it. A println() after the inner loop, still inside the outer loop, ends one row per outer pass, so each row holds what the inner loop printed on that pass.
for (int i = 1; i <= 3; i++)
{
for (int j = 0; j < 4; j++)
{
System.out.print(i);
}
System.out.println();
}
The outer loop gives 3 rows, and on each one the inner loop prints i four times:
1111
2222
3333
Check yourself
Show answerHide answer
Every row would be 0123, printed three times, because j runs 0, 1, 2, 3 on each outer pass.
Worked example 1: Trace a triangle pattern
Question: What is printed when this code segment runs?
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j);
}
System.out.println();
}
What tells you the method
print inside the inner loop and println after it: trace row by row.
Step 1: Find the number of rows.
itakes the values 1, 2 and 3, andprintln()runs once per outer pass, so there are 3 rows.WhyEach row ends at the
println()that follows the inner loop.Step 2: Trace the inner loop on each pass.
iValues of jRow printed 1 1 1 2 1, 2 12 3 1, 2, 3 123 WhyThe bound
j <= imakes the inner loop runitimes, printing 1 up toi.Step 3: Write the rows in order.
The digits in a row run together.
Whyprint(j)adds no spaces between values.
Check it
Count the digits: 1 + 2 + 3 = 6, the same as the total number of inner passes.
Answer
1 then 12 then 123, each on its own line.
Worked example 2: Count passes when the inner loop shrinks
Question: What is printed when this code segment runs?
int count = 0;
for (int i = 0; i < 5; i++)
{
for (int j = i; j < 5; j++)
{
count++;
}
}
System.out.println(count);
What tells you the method
The inner loop starts at i, so its count changes on each outer pass: add, don't multiply.
Step 1: Count the inner passes for each value of
i.ijrunsInner passes countafter the pass0 0 to 4 5 5 1 1 to 4 4 9 2 2 to 4 3 12 3 3 to 4 2 14 4 4 to 4 1 15 Whyjstarts atiand stops before 5, so the inner loop runs 5 −itimes.Step 2: Read the final value.
After the outer loop ends,
countis 15, and the last line prints it.Whycount++runs once per inner pass, socountequals the total.
Check it
The total is 5 + 4 + 3 + 2 + 1, and n(n + 1) / 2 with n = 5 also gives 15.
Answer
15
Worked example 3: Choose the inner loop header
Question: This code segment is meant to print the pattern shown in the text block.
****
***
**
*
for (int row = 4; row >= 1; row--)
{
/* missing loop header */
{
System.out.print("*");
}
System.out.println();
}
Which header can replace /* missing loop header */?
- A)
for (int k = 0; k <= row; k++) - B)
for (int k = 1; k < row; k++) - C)
for (int k = 0; k < row; k++) - D)
for (int k = row; k < 4; k++)
What tells you the method
A "which code can replace" question: find the stars each row needs, then count each option's passes.
Step 1: Link each row to
row.rowtakes 4, 3, 2, 1 and the rows need 4, 3, 2, 1 stars, so the inner loop must run exactlyrowtimes.WhyOne
print("*")runs per inner pass.Step 2: Count each option's passes when
rowis 4.A gives 5, B gives 3, C gives 4 and D gives 0.
WhyStarting
kat 0 withk < rowgivesrowpasses;<=adds one, and starting at 1 with<loses one.
Check it
Test C on the last row, when row is 1: k takes only the value 0, so one star is printed, as the pattern needs.
Answer
C
Your turn
Question: What is printed when this code segment runs?
for (int a = 1; a <= 3; a++)
{
for (int b = 1; b <= 3; b++)
{
System.out.print(a * b);
}
System.out.println();
}
Step 1: Count the rows.
The outer loop gives 3 rows, and the inner loop prints 3 products on each.
Step 2: Trace the first row.
With
a= 1,btakes 1, 2 and 3, so the row is 123.Step 3: Your go: trace the rows for
a= 2 anda= 3.
Show the full solutionHide the solution
Step 3. With a = 2 the products are 2, 4 and 6, so the row is 246. With a = 3 they are 3, 6 and 9, so the row is 369.
Answer: 123 then 246 then 369, each on its own line.
Traps
Trap
The inner body runs (outer passes) + (inner passes) times.
It seems right because the code holds two loops, each with its own count. But the whole inner loop runs again on every outer pass, so with fixed bounds the counts multiply.
An outer loop runs 5 times and a fixed inner loop runs 3 times per pass. How many inner iterations is that?
15, from 5 × 3. Adding would wrongly give 8.
Trap
A println() inside the inner loop still ends one row per outer pass.
It seems right because that println() is inside the outer loop too. But it runs on every inner pass, so each value ends its own line; to end one row per outer pass, put it just after the inner loop's closing brace.
To end each row once, does System.out.println() go inside the inner loop or just after it?
Just after the inner loop's closing brace, still inside the outer loop.
What's examined
On the AP® Computer Science A exam (Unit 2: Selection and Iteration), nested loops appear in multiple-choice questions that ask what a code segment prints or which loop header produces a given pattern. In free response you write nested loops yourself, for example to visit every row and column of a 2D array. Check each loop's first and last pass: a bound that is one off changes every count.
Practice questions
- Recall An outer loop runs 6 times, and on each pass a fixed inner loop runs 4 times. How many times does the inner body run in total?
- A) 10
- B) 24
- C) 4
- D) 6
Show answer
Answer: B. The inner loop runs all 4 passes on each of the 6 outer passes, and 6 × 4 = 24.
Why the others are wrong:
- A adds the two counts instead of multiplying.
- C counts the inner passes for one outer pass only.
- D counts the outer passes only.
- Apply How many times does
count++run when this code segment runs?
int count = 0;
for (int i = 1; i <= 4; i++)
{
for (int j = 0; j < 2 * i; j++)
{
count++;
}
}
Show answer
Answer: 20
Marking points:
- The inner loop runs
2 * itimes: 2, 4, 6 and 8 fori= 1 to 4. - 2 + 4 + 6 + 8 = 20.
- Apply What is printed when this code segment runs?
for (int r = 3; r >= 1; r--)
{
for (int c = 1; c <= r; c++)
{
System.out.print(r);
}
System.out.println();
}
Show answer
Answer: 333 then 22 then 1, each on its own line.
Marking points:
rtakes 3, 2, 1, so there are 3 rows.- The inner loop runs
rtimes and printsreach time, notc.
- Exam-style The method below should print
rowslines, each holdingcolscopies of#. Give the number of the line that stops it working.
1: public static void box(int rows, int cols)
2: {
3: for (int r = 0; r < rows; r++)
4: {
5: for (int c = 0; c < rows; c++)
6: {
7: System.out.print("#");
8: }
9: System.out.println();
10: }
11: }
Show answer
Answer: Line 5.
Marking points:
- The inner loop sets the width of each line, so it must run
colstimes, but line 5 usesrows. box(2, 5)prints two lines of##instead of two lines of#####; changing line 5 toc < colsfixes it.
- Exam-style How many times is
xprinted when this code segment runs?
for (int i = 0; i < 4; i++)
{
for (int j = i + 1; j < 4; j++)
{
System.out.print("x");
}
}
- A) 6
- B) 10
- C) 16
- D) 12
Show answer
Answer: A. The inner counts for i = 0, 1, 2, 3 are 3, 2, 1 and 0, and they add to 6.
Why the others are wrong:
- B starts
jatiinstead ofi + 1, an off-by-one error that gives 4 + 3 + 2 + 1. - C multiplies 4 × 4 as if the inner loop always ran 4 times.
- D multiplies 4 × 3, using the first pass's inner count for every pass.
- Exam-style What is printed when this code segment runs?
int sum = 0;
for (int i = 1; i <= 3; i++)
{
for (int j = i; j <= 3; j++)
{
sum += j;
}
}
System.out.println(sum);
- A) 18
- B) 6
- C) 10
- D) 14
Show answer
Answer: D. The passes add 1 + 2 + 3 = 6, then 2 + 3 = 5, then 3, and 6 + 5 + 3 = 14.
Why the others are wrong:
- A starts
jat 1 on every pass, giving 6 three times. - B counts only the first outer pass.
- C adds
iinstead ofj: 1 three times, 2 twice and 3 once.
- Recall In a nested loop, which variable changes on every iteration of the inner body: the outer loop variable or the inner loop variable? Answer outer or inner.
Show answer
Answer: Inner. The inner loop variable changes on every inner iteration, while the outer variable changes only after the inner loop finishes.
Marking points:
- In the trace of
iandjfor two outer passes,jchanges on every printed line andionly every third line.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- The inner loop restarts and runs in full on every pass of the outer loop.
- Fixed bounds: total inner passes = outer passes × inner passes.
- Inner bound uses the outer variable: list each pass's inner count and add.
- 1 + 2 + … + n = n(n + 1) / 2 counts a triangle of passes.
- One
println()after the inner loop ends one row per outer pass.