Nested Loops

A loop can contain another loop. For each outer iteration, the inner loop completes all of its iterations.

Patterns and tables often use nested loops: rows on the outside and columns on the inside.

Visit a grid

public class Main {
    public static void main(String[] args) {
        for (int row = 1; row <= 2; row++) {
            for (int column = 1; column <= 3; column++) {
                System.out.print(row * column);
                if (column < 3) {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

Output:

1 2 3
2 4 6

Each cell contains its row multiplied by its column. The inner print keeps one row together, and println ends it.

Work multiplies across nested loops. A loop of 1,000 by 1,000 performs one million inner iterations.

Print a rectangle of stars with nested loops.