Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Nested Iteration

Lesson ~11 min read 8 MCQs

In simple terms: In simple terms, nested iteration is about putting one loop inside of another. The inner loop runs completely, over and over again, once for each single step of the outer loop.

Why this matters

Imagine you're on the yearbook committee, and your job is to create the big grid of student portraits. You don't just place photos randomly, right? You work systematically. You start with the first row, and you place every student's photo for that row, from left to right. Only when that row is completely full do you move down to the second row and repeat the process. Then the third, and so on, until the page is complete.

That "for each row, handle every column" process is exactly what nested iteration is in programming. It’s a powerful tool for working with grids, tables, pairs of items, and any data that has a two-dimensional structure. In this lesson, we’ll break down how to build and understand these "loops within loops" so you can tackle complex problems with a clear, systematic approach.

Concept overview

flowchart TD
    A[Start] --> B{Outer Loop Condition Met?};
    B -- No --> I[End];
    B -- Yes --> C{Inner Loop Condition Met?};
    C -- No --> G[Update Outer Loop Variable];
    G --> B;
    C -- Yes --> D[Execute Inner Loop Body];
    D --> E[Update Inner Loop Variable];
    E --> C;
This flowchart shows the execution path of a nested loop. The process starts and checks the outer loop's condition. If true, it enters a sub-loop that repeatedly checks the inner loop's condition, executes the inner loop's body, and updates the inner variable until the inner condition is false. Only then does the flow update the outer loop variable and return to check the outer loop's condition again.

Core explanation

Hello everyone, it's Saavi. Today we're diving into a concept that feels a little like a Russian nesting doll: nested iteration. It’s a fundamental skill, especially for handling anything that looks like a grid or requires comparing items within a set.

What is a Nested Loop?

At its core, a nested loop is simply a loop that lives inside another loop.

// The "outer" loop
for (int i = 0; i < 3; i++) {

    // The "inner" loop
    for (int j = 0; j < 5; j++) {
        // This code runs every time the inner loop iterates
        System.out.print("*");
    }

    // This code runs only when the inner loop finishes
    System.out.println();
}

The loop with the variable i is the outer loop. The loop with j is the inner loop.

The Golden Rule of Nested Loops

Here is the single most important rule to remember: For each one iteration of the outer loop, the inner loop runs to completion.

Think of a digital clock.

  • The outer loop is the hour.
  • The inner loop is the minute.

The hour doesn't tick forward to 3:00 until the minutes have gone all the way from 2:00, 2:01, 2:02... all the way to 2:59. The "minute loop" has to complete its entire 60-step cycle before the "hour loop" takes a single step forward.

Nested loops in Java work the exact same way. The outer loop starts, and then it pauses and hands control over to the inner loop. The inner loop runs and runs and runs until its condition is false. Only then does control return to the outer loop, which completes its first iteration and starts its second. Then the whole process repeats.

Tracing a Nested Loop

Let's trace the code from above to see this in action. The outer loop runs when i is 0, 1, and 2. The inner loop runs when j is 0, 1, 2, 3, and 4.

Tracing the nested loop that prints stars, showing how the inner loop completes for each outer loop iteration.

1. Outer loop starts. i is 0.

  • The program enters the outer loop's body.
  • It immediately encounters the inner loop.
  • Inner loop starts.
    • j is 0. Prints *.
    • j is 1. Prints *.
    • j is 2. Prints *.
    • j is 3. Prints *.
    • j is 4. Prints *.
    • j becomes 5. The inner loop condition j < 5 is now false.
  • Inner loop ends.
  • The program continues in the outer loop's body. It executes System.out.println(), moving the cursor to a new line.
  • The outer loop's first iteration is now complete.

Output so far:

*****

2. Outer loop continues. i is 1.

  • The program enters the outer loop's body again.
  • It encounters the inner loop.
  • Inner loop starts again from scratch.
    • j is 0. Prints *.
    • j is 1. Prints *.
    • ...and so on until j is 4.
  • Inner loop ends.
  • The System.out.println() runs again.

Output so far:

*****
*****

3. Outer loop continues. i is 2.

  • The process repeats one last time. The inner loop runs completely, printing 5 more asterisks. The println moves to the next line.

Final Output:

*****
*****
*****

The inner loop's body ran a total of 3 * 5 = 15 times. The outer loop's body ran 3 times.

Where Students Get Stuck

Remember the clock. The hour hand doesn't move every time the minute hand moves. It waits. The outer loop is patient. It waits for the inner loop to do all of its work before it continues.

Nested loops are your go-to tool for processing 2D data structures. Think of the outer loop as controlling the rows and the inner loop as controlling the columns.

  • for (int row = 0; ...)
  • for (int col = 0; ...)

This pattern is so common that you'll see it again when we get to 2D arrays in a later unit. Mastering the flow now will make your life so much easier down the road.

Understanding the 'Golden Rule' of nested loops: inner loop completes for each outer loop iteration.

See it in action

Java Code

      
      
Condition Check
Variables
Console Output

      
Step 0 / 0

Worked examples

Let's walk through a couple of examples to make this concrete.

Example 1

Printing a Numbered Triangle

Problem: Write code that produces the following output.

1
12
123
1234

Solution Walkthrough:

  1. 1
    Analyze the Structure
    We see multiple lines, so we know we need a System.out.println() to create the new lines. This suggests an outer loop that handles each row. There are 4 rows.
  2. 2
    Outer Loop
    Let's set up an outer loop that runs 4 times. We'll use a variable row that goes from 1 to 4.
    for (int row = 1; row <= 4; row++) {
        // What happens in each row?
        // ...
        System.out.println(); // Move to next line after the row is done
    }
  3. 3
    Analyze the Inner Pattern
    • In row 1, we print up to 1.
    • In row 2, we print up to 2.
    • In row 3, we print up to 3.
    • In row 4, we print up to 4.

    It looks like for each row, we need an inner loop that prints numbers from 1 up to the current row number. The inner loop's stopping point depends on the outer loop's current value.

  4. 4
    Inner Loop
    Let's create an inner loop using a variable col. It should start at 1 and go up to the current value of row.
    for (int col = 1; col <= row; col++) {
        System.out.print(col);
    }
  5. 5
    Combine and Finalize
    Now, we place the inner loop inside the outer loop.
Tracing the numbered triangle pattern, showing how `col` depends on `row`.
```java
public class Triangle {
    public static void main(String[] args) {
        for (int row = 1; row <= 4; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print(col);
            }
            System.out.println(); // Essential for creating the rows!
        }
    }
}
```
Example 2

Finding Duplicate Names in a Roster

Problem: Given an array of names, find and print any names that appear more than once. For a list like {"Maya", "Liam", "Sofia", "Maya", "Carlos"}, the program should identify "Maya".

Solution Walkthrough:

  1. 1
    The Core Task
    How do you find a duplicate? You have to compare every name on the list to every other name on the list.
  2. 2
    The Strategy
    This "every item vs. every other item" is a perfect use case for nested loops.
    • The outer loop will pick a name. Let's say it picks "Maya" at index 0.
    • The inner loop will then compare that chosen name to all the names that come after it in the list.
  3. 3
    Setting up the Loops
    Let's say our array is String[] names.
    String[] names = {"Maya", "Liam", "Sofia", "Maya", "Carlos"};
    
    // Outer loop picks the first name to compare
    for (int i = 0; i < names.length; i++) {
        // Inner loop picks the second name to compare
        for (int j = i + 1; j < names.length; j++) {
            // Compare names[i] and names[j]
        }
    }
  4. 4

    Why j = i + 1? This is the most critical part of this example.

    • We don't need to compare a name to itself (i should not equal j).
    • If we've already compared names[0] and names[2], we don't need to later compare names[2] and names[0]. It's the same comparison.
    • By starting j at i + 1, we ensure we only compare each pair once and we never compare an element to itself.
  5. 5
    Adding the Comparison
    Inside the inner loop, we use .equals() to compare the strings.
    if (names[i].equals(names[j])) {
        System.out.println("Found a duplicate: " + names[i]);
    }
  6. 6
    Full Code
    public class FindDuplicates {
        public static void main(String[] args) {
            String[] names = {"Maya", "Liam", "Sofia", "Maya", "Carlos"};
            for (int i = 0; i < names.length; i++) {
                for (int j = i + 1; j < names.length; j++) {
                    if (names[i].equals(names[j])) {
                        System.out.println("Found a duplicate: " + names[i]);
                    }
                }
            }
        }
    }

    When i is 0 (names[i] is "Maya"), j will start at 1. The inner loop will compare "Maya" to "Liam", then "Sofia", then "Maya" (at index 3). It finds a match and prints.

Avoiding a common mistake: making the inner loop's condition fixed instead of dynamic.
Visualizing the nested loop for finding duplicate names.

Try it yourself

Ready to try on your own? Don't worry about getting it perfect on the first try. The goal is to think through the logic.

Problem 1: The Other Triangle

Write a program that uses nested loops to print the following pattern:

****
***
**
*

Problem 2: The Team-Up

You have an array of basketball players: String[] players = {"Jordan", "Priya", "Marcus", "Aaliyah"};. Write a program to print out every possible pair of two different players that can be formed from this list. The order doesn't matter (i.e., "Jordan and Priya" is the same as "Priya and Jordan").

Tracing the 'Other Triangle' problem with a decreasing inner loop.