Skip to main content

Nested Loops

beginner15 min readLesson 19 of 180

Loops inside loops: tables, triangles, pairwise work, and the first intuition of squaring cost.

A loop inside a loop multiplies work: for each pass of the outer loop, the inner loop runs completely.

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
        System.out.print(row * col + "\t");
    }
    System.out.println();          // end of row
}

This prints the 3×3 multiplication table. The structure to notice: the inner loop's work is part of the outer loop's body — and the newline goes after the inner loop, once per row. Misplacing one statement by a level turns a table into a diagonal.

Nested loops power grids, pairwise comparisons, and pattern printing:

for (int i = 1; i <= 4; i++) {
    for (int j = 0; j < i; j++) {
        System.out.print("*");
    }
    System.out.println();
}
// *
// **
// ***
// ****

Cost intuition. Doubling the data in a simple loop roughly doubles the work — linear. Doubling the data in a nested loop squares it: 1,000 × 1,000 is a million operations; 10,000 × 10,000 is a hundred million, and you feel it. When you meet a slow program later, nested loops over big data are the first suspect. This intuition (formalized as Big-O later) is the beginning of performance thinking.

Next: practice.