No history yet

Nested Loops

Loops Inside Loops

You're familiar with how loops repeat a block of code. But what happens when you put a loop inside another loop? This is called a nested loop. The concept is simple: for every single pass of the outer loop, the inner loop runs to completion.

Think of it like the hands of a clock. The hour hand (the outer loop) moves one position. In that single hour, the minute hand (the inner loop) must complete its full 60-minute cycle. Only after the minute hand is finished does the hour hand move to the next position. The same logic applies here.

// Outer loop
for (int i = 1; i <= 3; i++) {

    // Inner loop
    for (int j = 1; j <= 2; j++) {
        System.out.println("Outer: " + i + ", Inner: " + j);
    }

    System.out.println("-- Inner loop finished --\n");
}

Let's trace the execution of that code. When the outer loop starts, i is 1. The program then enters the inner loop. The inner loop runs completely while i remains 1:

  • j becomes 1. It prints "Outer: 1, Inner: 1".
  • j becomes 2. It prints "Outer: 1, Inner: 2".

The inner loop's condition (j <= 2) is now false, so it finishes. The program prints that the inner loop is finished and moves to the next iteration of the outer loop.

The process repeats. The outer loop sets i to 2. The inner loop then runs again from start to finish for j = 1 and j = 2. This continues until the outer loop's condition (i <= 3) is met.

Generating Patterns

Nested loops are perfect for creating two-dimensional patterns, like triangles and squares, because they work with a row-and-column structure. The outer loop typically controls the rows, while the inner loop controls the columns in each row.

Let's build a right-angled triangle of asterisks. We want the first row to have one asterisk, the second to have two, and so on. This means the number of columns (inner loop) depends on the current row number (outer loop).

int rows = 5;

// Outer loop for rows
for (int i = 1; i <= rows; i++) {

    // Inner loop for columns
    // The number of columns is equal to the current row number (i)
    for (int j = 1; j <= i; j++) {
        System.out.print("*"); 
    }

    // Move to the next line after the inner loop is done
    System.out.println(); 
}

Output: * **




The key is the inner loop's condition: j <= i. When i is 1, the inner loop runs once. When i is 2, it runs twice. This dynamic link between the loops creates the triangular shape.

We can use the same logic to create patterns with numbers. Instead of printing an asterisk, let's print the value of the inner loop's counter, j.

int rows = 4;

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

Output: 1 1 2 1 2 3 1 2 3 4

Beyond Visuals

Nested loops aren't just for drawing shapes. They are essential for solving problems that require checking items against a collection of other items. A classic example is finding all prime numbers within a given range.

To determine if a number is prime, we need to check if it's divisible by any number other than 1 and itself. A nested loop structure is ideal for this:

  1. An outer loop iterates through every number in our range (e.g., from 2 to 100).
  2. An inner loop checks if the current number from the outer loop is divisible by any number smaller than it.
// Find primes between 1 and 100
for (int i = 2; i <= 100; i++) {
    boolean isPrime = true;

    // Inner loop to check for factors
    // We only need to check up to the square root of i for efficiency,
    // but checking up to i/2 works just as well for demonstration.
    for (int j = 2; j <= i / 2; j++) {

        // If i is divisible by j, it's not a prime number
        if (i % j == 0) {
            isPrime = false;
            break; // Exit the inner loop, no need to check further
        }
    }

    if (isPrime) {
        System.out.print(i + " ");
    }
}

In this example, for each number i, we assume it's prime by setting isPrime to true. The inner loop then tries to prove that assumption wrong by finding a factor. If it finds one (i % j == 0), it sets isPrime to false and uses break to exit the inner loop immediately. If the inner loop completes without finding any factors, isPrime remains true, and the number is printed.

Quiz Questions 1/5

In a nested loop structure, how many times does the inner loop complete its entire cycle?

Quiz Questions 2/5

What is the output of the following code snippet?

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

Mastering nested loops is a big step. It allows you to work with multi-dimensional data and solve a much wider range of algorithmic challenges.