AP · Computer Science A · Loops

Nested Loops

14 min readUpdated December 1, 2026FreeAP Computer Science A, Selection and Iteration

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

  1. How many times does the body of for (int k = 0; k < 5; k++) run?Show answerHide answer

    Five times, with k equal to 0, 1, 2, 3 and 4. When k reaches 5, the condition k < 5 is false and the loop stops.

  2. 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 a to b inclusive runs b - a + 1 times.

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 print and println.
  • 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 printedij
1st11
2nd12
3rd13
4th21
5th22
6th23

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

In the code segment in this section, what are i and j when the 5th line is printed?
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

The outer loop is for (int a = 0; a < 3; a++) and the inner loop is for (int b = 0; b < 7; b++). How many times does the inner body run?
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

If the inner header in this section were for (int j = 1; j < i; j++), how many times would count++ run?
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

How would the output change if print(i) became print(j)?
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.

  1. Step 1: Find the number of rows.

    i takes the values 1, 2 and 3, and println() runs once per outer pass, so there are 3 rows.

    Why

    Each row ends at the println() that follows the inner loop.

  2. Step 2: Trace the inner loop on each pass.

    iValues of jRow printed
    111
    21, 212
    31, 2, 3123
    Why

    The bound j <= i makes the inner loop run i times, printing 1 up to i.

  3. Step 3: Write the rows in order.

    The digits in a row run together.

    Why

    print(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.

  1. Step 1: Count the inner passes for each value of i.

    ij runsInner passescount after the pass
    00 to 455
    11 to 449
    22 to 4312
    33 to 4214
    44 to 4115
    Why

    j starts at i and stops before 5, so the inner loop runs 5 − i times.

  2. Step 2: Read the final value.

    After the outer loop ends, count is 15, and the last line prints it.

    Why

    count++ runs once per inner pass, so count equals 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.

  1. Step 1: Link each row to row.

    row takes 4, 3, 2, 1 and the rows need 4, 3, 2, 1 stars, so the inner loop must run exactly row times.

    Why

    One print("*") runs per inner pass.

  2. Step 2: Count each option's passes when row is 4.

    A gives 5, B gives 3, C gives 4 and D gives 0.

    Why

    Starting k at 0 with k < row gives row passes; <= 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();
}
  1. Step 1: Count the rows.

    The outer loop gives 3 rows, and the inner loop prints 3 products on each.

  2. Step 2: Trace the first row.

    With a = 1, b takes 1, 2 and 3, so the row is 123.

  3. Step 3: Your go: trace the rows for a = 2 and a = 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

  1. 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.
  1. 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 * i times: 2, 4, 6 and 8 for i = 1 to 4.
  • 2 + 4 + 6 + 8 = 20.
  1. 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:

  • r takes 3, 2, 1, so there are 3 rows.
  • The inner loop runs r times and prints r each time, not c.
  1. Exam-style The method below should print rows lines, each holding cols copies 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 cols times, but line 5 uses rows.
  • box(2, 5) prints two lines of ## instead of two lines of #####; changing line 5 to c < cols fixes it.
  1. Exam-style How many times is x printed 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 j at i instead of i + 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.
  1. 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 j at 1 on every pass, giving 6 three times.
  • B counts only the first outer pass.
  • C adds i instead of j: 1 three times, 2 twice and 3 once.
  1. 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 i and j for two outer passes, j changes on every printed line and i only 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.

Keep learning

Prerequisites: for Loops

Explore AP Computer Science A tutoring →

View the full Computer Science A syllabus →

More in this unit

Selection and Iteration

All Loops notes

Part of Novark's AP Computer Science A notes