Skip to content

C Nested Loops

Updated 7 min read Aimerscrew

Many things in life come in rows and columns: cinema seats, spreadsheet cells, a chessboard, a calendar month. To visit every cell, you go through each row, and inside each row, through each column. In code, that means putting one loop inside another. These are called C nested loops. In this lesson, you'll learn how they run, how to draw patterns and build a multiplication table with them, why they can get slow, and how to break out of two loops at once.

🌍 Real-life example

An usher checking tickets in a cinema walks to row A and checks seats 1, 2, 3 and 4. Then they move to row B and start again from seat 1, and so on. The usher changes rows slowly (the outer loop) and changes seats quickly (the inner loop). For every row, they visit all the seats in it.

What is a nested loop in C?

A nested loop is a loop written inside the body of another loop. The outer loop controls the "big" steps (rows), and the inner loop does the "small" steps (columns) for each one. Here's the cinema with 3 rows and 4 seats per row:

#include <stdio.h>

int main(void) {
    for (int row = 0; row < 3; row++) {
        for (int seat = 1; seat <= 4; seat++) {
            printf("[%c%d]", 'A' + row, seat);
        }
        printf("\n");
    }
    return 0;
}
[A1][A2][A3][A4]
[B1][B2][B3][B4]
[C1][C2][C3][C4]

Two details make this work. 'A' + row turns the row number into a letter: characters are stored as numbers, so 'A' + 1 is 'B' (see C data types). And the printf("\n") sits after the inner loop but inside the outer one, so it ends each row with a new line.

How do nested loops run step by step?

The key rule: the inner loop finishes all of its iterations before the outer loop moves one step. Then the inner loop starts over from the beginning. This program prints every step so you can see the order:

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 2; i++) {
        printf("Outer i = %d\n", i);
        for (int j = 1; j <= 3; j++) {
            printf("  inner j = %d\n", j);
        }
    }
    printf("Done.\n");
    return 0;
}
Outer i = 1
  inner j = 1
  inner j = 2
  inner j = 3
Outer i = 2
  inner j = 1
  inner j = 2
  inner j = 3
Done.
Animation of nested loops over cinema seats: the outer loop arrow stays on row A while the inner loop highlight visits seats A1 to A4, then the outer loop moves to row B and the inner loop starts again at seat 1, until all 12 seats in rows A to C are visited
The outer loop moves one row at a time; the inner loop sweeps every seat in that row.

You can nest any kind of loop: a while loop inside a for loop, a for loop inside a do-while loop, and so on. Nested for loops are the most common because rows and columns usually have known sizes.

How do you print a rectangle of stars?

Pattern printing is the classic way to practice nested loops. The outer loop prints rows, the inner loop prints the characters in one row:

#include <stdio.h>

int main(void) {
    int rows = 3;
    int cols = 5;

    for (int r = 1; r <= rows; r++) {
        for (int c = 1; c <= cols; c++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
*****
*****
*****

How do you print a triangle pattern in C?

For a triangle, each row has a different length. The trick is to make the inner loop's limit depend on the outer loop's variable: row 1 gets 1 star, row 2 gets 2 stars, and so on.

#include <stdio.h>

int main(void) {
    int height = 4;

    for (int row = 1; row <= height; row++) {
        for (int star = 1; star <= row; star++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
*
**
***
****

To push the triangle to the right, print some spaces first. Row row needs height - row spaces, then row stars. That's two inner loops, one after the other, inside the same outer loop:

#include <stdio.h>

int main(void) {
    int height = 4;

    for (int row = 1; row <= height; row++) {
        for (int space = 1; space <= height - row; space++) {
            printf(" ");
        }
        for (int star = 1; star <= row; star++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
   *
  **
 ***
****

💡 Tip

Before coding any pattern, write a small table on paper: for each row, how many spaces and how many stars? Once you see the rule (like "spaces = height - row"), the loops almost write themselves.

Building a multiplication table grid

Nested loops are perfect for tables. The value in each cell is simply row * col:

#include <stdio.h>

int main(void) {
    for (int row = 1; row <= 5; row++) {
        for (int col = 1; col <= 5; col++) {
            printf("%4d", row * col);
        }
        printf("\n");
    }
    return 0;
}
   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 prints each number right-aligned in a space 4 characters wide, so the columns line up whether a number has one digit or two. You saw field widths in C format specifiers.

How many times does a nested loop run?

Multiply the counts. If the outer loop runs R times and the inner loop runs C times each, the inner body runs R × C times. The cinema had 3 × 4 = 12 seats. When both loops go up to the same number n, the body runs n × n times, and that grows fast:

#include <stdio.h>

int main(void) {
    for (int n = 10; n <= 1000; n *= 10) {
        long steps = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                steps++;
            }
        }
        printf("n = %d -> %ld steps\n", n, steps);
    }
    return 0;
}
n = 10 -> 100 steps
n = 100 -> 10000 steps
n = 1000 -> 1000000 steps

Making n 10 times bigger made the work 100 times bigger. Programmers describe this as O(n²) ("order n squared") time. You don't need the math yet, just the intuition: each extra level of nesting multiplies the work. That's fine for a 5 × 5 table, but worth thinking about when n is a million. (This example even nests three loops: the outer one just tries different sizes.)

How do you break out of nested loops?

As you learned in break and continue, break only exits the innermost loop. To stop both loops, set a flag (a variable that remembers "we're done") and check it in the outer loop.

Say a bakery wants to pack exactly 42 cookies in a tray of rows × columns, with at most 9 of each. Find the first layout that works:

#include <stdio.h>

int main(void) {
    int found = 0;
    int rows = 0;
    int cols = 0;

    for (int r = 1; r <= 9; r++) {
        for (int c = 1; c <= 9; c++) {
            if (r * c == 42) {
                rows = r;
                cols = c;
                found = 1;
                break;          // leaves the inner loop only
            }
        }
        if (found) {
            break;              // leaves the outer loop too
        }
    }

    if (found) {
        printf("42 cookies fit in %d rows of %d.\n", rows, cols);
    } else {
        printf("No layout found.\n");
    }
    return 0;
}
42 cookies fit in 6 rows of 7.

Without the second break, the outer loop would carry on to row 7 and find another match (7 rows of 6), overwriting the first answer. Some C programmers use goto to jump out of deep loops, but a flag is easier for everyone to read.

Common mistakes with nested loops

1. Sharing one counter between both loops

int i;
for (i = 0; i < 3; i++) {
    for (i = 0; i < 4; i++) {
        printf("*");
    }
    printf("\n");
}

The inner loop leaves i at 4, the outer loop adds 1 to make it 5, and 5 < 3 is false. Only one row of four stars is printed instead of three rows. Give each loop its own variable (i and j, or better, row and col).

2. Putting the newline in the wrong place

If printf("\n") goes inside the inner loop, every star lands on its own line. If it goes outside both loops, everything ends up on one line. It belongs after the inner loop, inside the outer one.

3. Expecting one break to stop everything

A break in the inner loop only ends the current row. The outer loop moves on to the next row. Use a flag, as shown above.

4. Using the wrong limit in the inner loop

For a triangle, the inner condition must use the outer variable (star <= row). Writing star <= height by mistake prints a rectangle instead.

Practice exercise

🏋️ Try it yourself

Print a number triangle with 4 rows using nested loops. Each row counts from 1 up to the row number, so the rows are 1, 12, 123 and 1234.

Show solution
#include <stdio.h>

int main(void) {
    int height = 4;

    for (int row = 1; row <= height; row++) {
        for (int num = 1; num <= row; num++) {
            printf("%d", num);
        }
        printf("\n");
    }
    return 0;
}
1
12
123
1234

It's the star triangle again, but printing the inner loop's counter instead of a *.

What's next?

Congratulations, you've finished the Control Flow chapter! Your programs are getting longer, so it's time to split them into reusable, named pieces. Start the next chapter with C functions.

Key takeaways

  • A nested loop is a loop inside the body of another loop.
  • For each iteration of the outer loop, the inner loop runs all of its iterations from the start.
  • An outer loop of R steps and an inner loop of C steps run the inner body R × C times; n × n work grows very fast.
  • Nested loops suit rows and columns: seat maps, grids, tables and star patterns.
  • Make the inner limit depend on the outer variable to print triangles.
  • break exits only the innermost loop; use a flag variable to leave both loops.
  • Give each loop its own counter variable.

Frequently asked questions

What is a nested loop in C?

A nested loop is a loop placed inside another loop. The outer loop handles the big steps, such as rows, and the inner loop runs completely for each of them, handling the small steps, such as columns.

How many times does a nested loop run?

Multiply the iteration counts. An outer loop that runs 3 times with an inner loop that runs 4 times executes the inner body 3 × 4 = 12 times. Two loops up to n run n × n times.

How do I break out of two nested loops in C?

break only exits the innermost loop. Set a flag variable such as found = 1 before breaking from the inner loop, then check the flag right after the inner loop and break from the outer loop as well.

Can I nest a while loop inside a for loop?

Yes. Any loop type can be nested inside any other: for, while and do-while can be combined freely. Nested for loops are most common because grid sizes are usually known.

Why are nested loops slow?

Each level of nesting multiplies the work. Two loops up to n do n × n steps, so 1,000 items mean a million steps. This is called O(n²) time and matters for large inputs.