Nested Loops

Naveen AnamaneniUpdated · 4 min read

A cinema hall has rows, and every row has seats. To check every seat, you walk row by row, and in each row you go seat by seat. That's two loops, one inside the other: a nested loop. The inner loop runs completely for every single round of the outer loop.

Rows and Seats

The inner loop runs fully for every round of the outer loop
Seats.java▶ Try it
public class Seats {
    public static void main(String[] args) {
        for (char row = 'A'; row <= 'C'; row++) {
            for (int seat = 1; seat <= 4; seat++) {
                System.out.print(row + "" + seat + " ");
            }
            System.out.println();
        }
    }
}
Output
A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4

How it works

  1. Line 3, the outer loop, picks a row: A, then B, then C.
  2. Line 4, the inner loop, runs seats 1 to 4 for that row, then finishes.
  3. Line 7 ends the line after each row. Then the outer loop moves to the next row, and the inner loop starts again from seat 1.
  4. Total: 3 rows × 4 seats = 12 rounds of the inner body.

row + "" + seat joins the two as text. Without the empty string, row + seat would add the char and the int as numbers.

Try it yourself: swap the two loops so seats are on the outside. How does the printed grid change?

A Multiplication Table

Table.java▶ Try it
public class Table {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                System.out.printf("%4d", i * j);
            }
            System.out.println();
        }
    }
}
Output
   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

%4d gives every number 4 characters, so the columns line up (see "Format Specifiers").

When the Inner Loop Depends on the Outer

The inner loop's limit can use the outer variable. This prints a triangle, where row i has i stars:

Triangle.java▶ Try it
public class Triangle {
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Output
*
**
***
****

The lesson "Basic Java Programs" has more patterns like this.

Common Mistakes

Reusing the same counter name. Using i for both loops doesn't compile when the scopes overlap. Use i and j, or better, row and seat.

Putting println() inside the inner loop. Every value then lands on its own line instead of forming a row.

Expecting break to leave both loops. A plain break leaves only the innermost loop. The lesson "Labeled Break and Continue" shows how to leave both.

Practice

  1. Easy: Print a 4 × 6 rectangle of # characters.
  2. Harder: Print the multiplication table from 1 to 9, but only the half where j <= i (a triangle of products).

Quick check: Nested loops

4 questions
1An outer loop runs 3 times and the inner loop runs 4 times each. How many times does the inner body run?
2When does the inner loop start again from its first value?
3Where should System.out.println() go to end each row of a grid?
4What does a plain break inside the inner loop do?

Key Takeaways

Was this tutorial helpful?

Lesson 61 of 482