Skip to main content

Nested Loops and Patterns

beginner11 min readLesson 19 of 148

Rows and columns: loops inside loops, the grid mental model, and printing shapes.

The grid model

A loop inside a loop is a grid: the outer loop is ROWS, the inner is COLUMNS. The inner loop runs completely for each single step of the outer loop.

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= row; col++) {
        printf("*");
    }
    printf("\n");
}

Output:

*
**
***

Trace before you run

Say it out loud: row 1 prints 1 star; row 2 prints 2; row 3 prints 3. The inner bound depends on the OUTER variable โ€” that is what makes a triangle, not a rectangle.

Cost intuition

3 rows x 3 columns = 9 inner steps. Doubling the side quadruples the work โ€” loops multiply, and this intuition becomes Big-O thinking later.

Now practice

Pattern FactoryNested loops producing exact shapes and tables.3 challenges ยท ยท ~14 min