Reference Guide

Key Ideas

  • Nested iteration is a loop inside the body of another loop.
  • The inner loop runs completely (all of its passes) for each single pass of the outer loop.
  • When the loops are independent, the inner body runs outer count * inner count times. 3 rows of 4 columns is 12 cells.
  • The inner loop can depend on the outer variable, for example j <= i. That makes triangles instead of rectangles.
  • System.out.print stays on the same line; System.out.println() after the inner loop ends the row.
  • Trace nested loops by tracking the outer and inner variables separately.

Rectangle Versus Triangle

Rectangle (independent) Triangle (dependent)
for (int i = 1; i <= 3; i++) {
  for (int j = 1; j <= 4; j++) {
    System.out.print("*");
  }
  System.out.println();
}
for (int i = 1; i <= 3; i++) {
  for (int j = 1; j <= i; j++) {
    System.out.print("*");
  }
  System.out.println();
}
****
****
**** (12 stars)
*
**
*** (6 stars)

College Board Requirements

AP CSA Unit 2, Topic 2.11: Nested Iteration.

This lesson is built directly against the College Board’s stated learning objective for this topic:

Represent nested iterative processes.

Topic 2.11, Nested Iteration, is required content on the AP Computer Science A Exam. The learning objective quoted above is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.


Lesson Plan

Learning Objective: Represent nested iterative processes.

Success Criteria: You can put one loop inside another, state exactly how many times the inner body runs, and build a rectangular or triangular pattern from the two loop variables.

Tech Talk & Introduction

A nested loop is a loop whose body contains another loop. The inner loop finishes completely on every single pass of the outer loop.

  • For an outer loop of m passes and an inner loop of n passes, the inner body runs m * n times.
  • When the inner bound depends on the outer variable, the total is the sum of the inner counts, not a simple product. That is what produces triangles instead of rectangles.
  • System.out.print keeps output on one line; System.out.println() after the inner loop ends the row.

Code Examples

A. Simple: Nested Loops in Code

A multiplication table. Run it, then change size to 5 and 10.

Code Runner Challenge

Multiplication table: the inner loop prints one row, the outer loop repeats it.

View IPYNB Source
// CODE_RUNNER: Multiplication table: the inner loop prints one row, the outer loop repeats it.
public class TimesTable {
    public static void main(String[] args) {
        int size = 6;   // try 5 and 10

        for (int row = 1; row <= size; row++) {
            for (int col = 1; col <= size; col++) {
                int product = row * col;
                if (product < 10) {
                    System.out.print(" ");   // pad single digits so columns line up
                }
                System.out.print(product + " ");
            }
            System.out.println();
        }
    }
}
TimesTable.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hacks & Practice Tasks

Activity 1: Trace the Grid

Step through it and watch j restart from 1 every time i changes. The grid on the right lights up one cell per inner pass.

Rows and Columns
The inner loop finishes a whole row before the outer loop moves down.

Activity 2: Pattern Builder

Change the rows and the pattern. Read the code to see why the inner loop bound is different for each shape.

Pattern Builder
The inner loop bound decides the shape.

Activity 3: How Many Stars?

Count the Inner Passes
Predict the total number of stars, then run.

Activity 4: Predict the Output

Nested Loop Questions
Track the two variables separately.
Question 1

What does this print?

for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + " ");
}
}
Question 2

How many times does the inner println run?

for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j += 2) {
System.out.println(i + j);
}
}
Question 3

Which change makes this print a 5 by 5 square of stars instead of a triangle?

for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}

Popcorn Hack

Print a right triangle of numbers where each row counts up to the row number:

1
1 2
1 2 3
1 2 3 4

Code Runner Challenge

Popcorn hack: number triangle with nested loops.

View IPYNB Source
// CODE_RUNNER: Popcorn hack: number triangle with nested loops.
public class NumberTriangle {
    public static void main(String[] args) {
        int rows = 4;

        // TODO: outer loop for the rows, inner loop that prints 1 through i,
        //       and a println after each row
    }
}
NumberTriangle.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Homework Hack

Two short tasks.

  1. Finish the runner: count the pairs (a, b) with 1 <= a < b <= n whose sum is even. For n = 4 the pairs are (1,3) and (2,4), so the answer is 2.
  2. Answer the quick check.

Code Runner Challenge

Homework: count pairs with an even sum using nested loops. Expected for 4: 2.

View IPYNB Source
// CODE_RUNNER: Homework: count pairs with an even sum using nested loops. Expected for 4: 2.
public class EvenPairs {
    public static void main(String[] args) {
        int n = 4;   // test 4 (2), 5 (4), 6 (6)
        int pairs = 0;

        // TODO: outer loop a from 1 to n, inner loop b from a + 1 to n,
        //       count the pair when (a + b) % 2 == 0

        System.out.println("Even-sum pairs: " + pairs);
    }
}
EvenPairs.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
Homework Quick Check
Type a number.

How many times does total++ run?

int total = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
total++;
}
}

References

College Board Course and Exam Description

Topic 2.11, Nested Iteration, is required content on the AP Computer Science A Exam. The learning objective quoted in section 3 (College Board Requirements) is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.

Outside Academic Reference

A nested loop is simply an iteration statement appearing as the body of another; no separate construct is defined, which is why the inner loop’s own termination rules apply in full on every outer pass.

Reference List

College Board. (2025). AP Computer Science A: Course and exam description. https://apcentral.collegeboard.org/courses/ap-computer-science-a

Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., Smith, D., & Bierman, G. (2023). The Java language specification: Java SE 21 edition. Oracle America. https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.14

All Java lessons