PrepGo

Nested Iteration - AP Computer Science A Study Guide

Written by AP Content Team, Verified for 2026 AP Exams, Last updated: May 2026

Learn with study guides reviewed by top AP teachers. This guide takes about 8 minutes to read.

Getting Started

Many programming problems involve processing data that is organized in two dimensions, like a grid of pixels on a screen, a spreadsheet, or a game board. To work with such structures, we need a way to repeat an action for each column within each row. Nested iteration provides a powerful and elegant solution for handling these multi-dimensional tasks by placing one loop inside another.

What You Should Be Able to Do

  • Write nested for loops to create patterns or process grid-like data structures.

  • Trace the values of the outer and inner loop control variables throughout the execution of a nested loop.

  • Determine the exact number of times a statement inside a nested loop will execute.

  • Describe the execution path of a program that contains nested loops.

Key Concepts & Java Implementation

The Core Idea

Nested iteration occurs when one loop, called the inner loop, is placed inside the body of another loop, called the outer loop. The fundamental principle is that the inner loop must complete all of its iterations for each single iteration of the outer loop.

Think of a clock. The hour hand is the outer loop, and the minute hand is the inner loop. For the hour hand to move just one position (e.g., from 1 to 2), the minute hand must complete its entire cycle of 60 positions. Similarly, in a nested loop, the outer loop proceeds to its next step only after the inner loop has run to completion. This structure is ideal for tasks that require iterating over rows and columns, where for each row (outer loop), you must process every column (inner loop).

Syntax & Implementation

The most common way to implement nested iteration in Java is with two for loops. The syntax follows a clear pattern.

General Structure:


// Outer loop

for (/* initialization */; /* condition */; /* update */) {

    

    // Code in the outer loop, but before the inner loop, runs once per outer iteration.


    // Inner loop

    for (/* initialization */; /* condition */; /* update */) {

        // This is the body of the inner loop.

        // This code runs (outer iterations) * (inner iterations) times.

    }


    // Code in the outer loop, but after the inner loop, runs once per outer iteration.

}

Annotated Java Examples

Example 1: Printing a 3x5 Rectangle

This code uses an outer loop for the rows and an inner loop for the columns to print a simple rectangle of asterisks.


public class RectanglePrinter {

    public static void main(String[] args) {

        int rows = 3;

        int cols = 5;


        // The outer loop controls the rows. It will run 3 times.

        for (int r = 0; r < rows; r++) {

            

            // The inner loop controls the columns. It runs 5 times for EACH outer loop iteration.

            for (int c = 0; c < cols; c++) {

                System.out.print("* "); // Print an asterisk without a new line.

            }


            // This statement is crucial. It moves the cursor to the next line after each row is complete.

            System.out.println(); 

        }

    }

}

Output:


* * * * * 

* * * * * 

* * * * * 

Example 2: Printing Coordinates

This example makes the relationship between the loop control variables explicit by printing their values.


public class CoordinatePrinter {

    public static void main(String[] args) {

        // The outer loop variable 'i' will go from 0 to 2.

        for (int i = 0; i < 3; i++) {

            // The inner loop variable 'j' will go from 0 to 1 for EACH value of 'i'.

            for (int j = 0; j < 2; j++) {

                System.out.println("Coordinates: (" + i + ", " + j + ")");

            }

        }

    }

}

Tracing & Analysis

Execution Trace

Let's trace the CoordinatePrinter example to see how the variables change and what the output is at each step.

Outer Loop (i)Inner Loop (j)Output
0(starts)
00Coordinates: (0, 0)
01Coordinates: (0, 1)
0(ends)
1(starts)
10Coordinates: (1, 0)
11Coordinates: (1, 1)
1(ends)
2(starts)
20Coordinates: (2, 0)
21Coordinates: (2, 1)
2(ends)
(ends)

Analysis

The total number of times the innermost statement executes is the product of the number of iterations of all enclosing loops.

  • In the RectanglePrinter example, the outer loop runs 3 times and the inner loop runs 5 times. The System.out.print("* "); statement executes 3 * 5 = 15 times.

  • In the CoordinatePrinter example, the outer loop runs 3 times and the inner loop runs 2 times. The System.out.println(...) statement executes 3 * 2 = 6 times.

This multiplicative relationship is a key characteristic of nested loops.

Java Syntax Quick-Reference

This topic combines existing Java syntax in a new structure.

  • for (int i = 0; i < limit; i++): The standard structure for a for loop, used to control iteration.

  • for (...) { for (...) { ... } }: The general pattern for nested iteration, where one for loop is placed inside the body of another.

Core Code Examples & Terminology

  • Iteration: A single execution of the body of a loop.

  • Nested Iteration: A control structure where one iterative statement is placed inside another, causing the inner loop to run to completion for each iteration of the outer loop.

  • Outer Loop: In a nested structure, the loop that contains the other. Its control variable typically changes more slowly.

  • Inner Loop: In a nested structure, the loop that is contained within the other. Its control variable typically changes more quickly, "resetting" for each outer loop iteration.

  • Core Snippet 1: Printing a Square Grid

    
    for (int r = 0; r < 4; r++) {
    
        for (int c = 0; c < 4; c++) {
    
            System.out.print("# ");
    
        }
    
        System.out.println();
    
    }
    

    This code prints a 4x4 grid of # symbols by using an outer loop for rows and an inner loop for columns.

  • Core Snippet 2: Printing a Right Triangle

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

    This code creates a triangle because the inner loop's condition (j <= i) depends on the outer loop's variable, causing it to run more times with each new row.

Core Skill Check

  • Code Tracing: What is the final value of sum after this Java code runs: int sum = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { sum++; } }?

    • Answer: 12
  • Debugging: Identify the logical error in this Java code intended to print a 3x3 grid: for (int r = 0; r < 3; r++) { for (int c = 0; c < 3; c++) { System.out.print("*"); } } System.out.println();.

    • Answer: The System.out.println(); is outside the outer loop, so all asterisks will print on a single line. It should be inside the outer loop but after the inner loop.
  • Application: Write a single line of Java code that prints the product of an outer loop variable i and an inner loop variable j.

    • Answer: System.out.println(i * j);

Common Misconceptions & Errors

  • Miscalculating Iterations: Thinking the total number of inner loop executions is the sum of the loop counts (e.g., 3 + 5 = 8) instead of the product (3 * 5 = 15).

  • Mixing Loop Variables: Accidentally using the outer loop's control variable in the inner loop's condition or update expression, or vice versa (e.g., for (int j = 0; j < 5; i++)). This can lead to infinite loops or incorrect behavior.

  • Misplacing println(): Placing the System.out.println() statement inside the inner loop, which creates a new line for every single element instead of at the end of each row.

  • Forgetting the Inner Loop "Resets": The inner loop's initialization statement (int j = 0) runs again for every single iteration of the outer loop. It does not pick up where it left off.

Summary

Nested iteration is a fundamental programming pattern where a loop is placed within the body of another loop. This structure is essential for processing two-dimensional data, such as grids, tables, or matrices. The key principle to remember is that the inner loop executes completely for each single iteration of the outer loop. Understanding how to trace the loop control variables is critical to predicting the output and behavior of the code. The total number of times the innermost code block runs is the product of the iteration counts of the outer and inner loops, making this a powerful but computationally significant structure.