Skip to main content

Nested Loops and Shapes

beginner10 min readLesson 15 of 204

Loops inside loops: grids, tables, and triangle patterns — and how to reason about the cost of nesting.

The grid shape

for (int row = 0; row < 3; ++row) {
    for (int col = 0; col < 4; ++col) {
        std::cout << row << ',' << col << ' ';
    }
    std::cout << '\n';       // end of one row
}

The inner loop runs completely for each single step of the outer loop: 3 × 4 = 12 iterations. The newline after the inner loop is what gives the output its shape.

Classic patterns (you will build these in practice)

*            1
* *          1 2
* * *        1 2 3

Triangle one: outer loop counts rows r, inner loop prints r stars. Triangle two: inner prints numbers 1..r. Neither is about stars — both are about controlling an inner loop's range from the outer loop's current value.

Tables

Multiplication tables pair a row loop with a column loop and format with padding. Nested loops over rows and columns are also exactly how you will later iterate 2-D data (vector<vector<int>> — module 7) and how image/flood-fill algorithms begin.

The cost of nesting

3 × 4 = 12 is nothing. But 1,000 × 1,000 = 1,000,000 — and 10,000 × 10,000 takes seconds even in C++. When you nest, multiply the sizes in your head first; it is your first complexity instinct (module 18 develops it properly).