Topic 52 of 100 Control Flow in C Interactive Tutorial

Nested Loops in C: Combining Multiple Repetition Levels

12 mins read Last updated: 22 Aug 2026 21,900 views
C Compiler 0.00%

What is Nested Loops in C? Core Concept & Direct Summary

Core Objective & Problem Statement

How do nested loops iterate across multi-dimensional spaces like matrices, tables, and geometric coordinate grids?

Direct Answer Summary

One loop repeats a task. But what if the task itself contains repetition? Printing a grid means repeating a row — and each row means repeating a cell. Checking every seat in a theater means walking every row — and every row means checking every seat. One level of repetition nested inside another.

That's exactly what a nested loop is: a complete loop living inside the body of another loop. It's not a new statement — just for, while, or do-while placed inside each other — but the combination unlocks an entirely new class of programs: grids, tables, patterns, matrices, and anything two-dimensional.

Nested loops are also where many beginners first feel lost. The counters tangle, the output surprises, and the trace gets hard to follow. This tutorial fixes that permanently with one core mental model, a step-by-step trace, and the classic pattern programs that build real loop intuition.

(Suggested image: the hero diagram — two concentric circles; the outer circle makes 3 slow turns while the inner circle spins 4 fast turns per outer turn — the "clock hands" analogy visualized)

How Does Nested Loops in C Work? In-Depth Mechanics & Architecture

The One Mental Model You Need

Before any syntax, burn this image into your brain:

The inner loop runs COMPLETELY — from start to finish — for every single iteration of the outer loop.

Think of a clock: the minute hand (inner) makes a full revolution before the hour hand (outer) advances once. Or a gym workout: for each set (outer), you do all ten reps (inner).

So this innocent-looking code:

main.c
Run Online
for (int i = 1;
i <= 3;
i++) {
    // outer: 3 iterations    for (int j = 1;
    j <= 4;
    j++) {
        // inner: 4 iterations EACH time        printf("*");
    }
    printf("\n");
}

...runs the inner body 3 × 4 = 12 times — not 3, not 4, not 7:

Total inner iterations = outer count × inner count. Every confusion about nested loops dissolves once this multiplication is instinctive.


The Step-by-Step Trace

Watch the counters move:

main.c
Run Online
for (int i = 1;
i <= 3;
i++) {
    for (int j = 1;
    j <= 2;
    j++) {
        printf("i=%d j=%d\n", i, j);
    }
}
Outer (i)Inner (j)Output
11i=1 j=1
12i=1 j=2
21 (restarts!)i=2 j=1
22i=2 j=2
31 (restarts!)i=3 j=1
32i=3 j=2

Output:

main.c
Run Online
i=1 j=1i=1 j=2i=2 j=1i=2 j=2i=3 j=1i=3 j=2

Notice the rhythm: i holds perfectly still while j cycles through its full range, and j restarts from 1 every time the outer loop advances. That restart is the detail people forget — the inner loop is born fresh on every outer pass, initialization and all.

(Suggested image: this trace table as an infographic with a timeline — the single most useful visual on this page)


Any Loop Can Nest Inside Any Loop

Nesting isn't a for-only feature. All combinations are legal:

main.c
Run Online
// for inside while:int i = 1;
while (i <= 3) {
    for (int j = 1;
    j <= i;
    j++) {
        printf("%d ", j);
    }
    printf("\n");
    i++;
}
// while inside for:for (int row = 1;
row <= 3;
row++) {
    int col = 1;
    while (col <= 4) {
        printf("# ");
        col++;
    }
    printf("\n");
}

In practice, for-inside-for dominates (counted grids are its home turf), but the mechanics are identical for every combination: inner completes, outer advances, inner restarts.


The Pattern Programs: Where Nested Loops Become Fun

Every C course assigns star patterns, and there's a reason they've survived decades — they force you to find the formula connecting the row number to the inner count. That skill transfers to everything.

Pattern 1: The Square

main.c
Run Online
for (int i = 1;
i <= 4;
i++) {
    for (int j = 1;
    j <= 4;
    j++) {
        // inner count: constant 4        printf("* ");
    }
    printf("\n");
}
main.c
Run Online
* * * ** * * ** * * ** * * *

Pattern 2: The Right Triangle

The trick: inner count equals the row number.

main.c
Run Online
for (int i = 1;
i <= 5;
i++) {
    for (int j = 1;
    j <= i;
    j++) {
        // row 1→1 star, row 2→2 stars...        printf("* ");
    }
    printf("\n");
}

Pattern 3: The Inverted Triangle

Inner count shrinks as the row grows: n - i + 1.

main.c
Run Online
int n = 5;
for (int i = 1;
i <= n;
i++) {
    for (int j = 1;
    j <= n - i + 1;
    j++) {
        printf("* ");
    }
    printf("\n");
}

Pattern 4: The Pyramid (The Famous One)

Two inner loops: one for leading spaces, one for stars. Spaces shrink (n - i), stars grow odd (2*i - 1):

main.c
Run Online
int n = 5;
for (int i = 1;
i <= n;
i++) {
    for (int s = 1;
    s <= n - i;
    s++) {
        // spaces: 4, 3, 2, 1, 0        printf(" ");
    }
    for (int j = 1;
    j <= 2 * i - 1;
    j++) {
        // stars: 1, 3, 5, 7, 9        printf("*");
    }
    printf("\n");
}
main.c
Run Online
* *** ***** ****************

Pattern 5: Number Triangle

main.c
Run Online
for (int i = 1;
i <= 4;
i++) {
    for (int j = 1;
    j <= i;
    j++) {
        printf("%d ", j);
    }
    printf("\n");
}

Don't memorize these. Derive them with one question: "In row i, how many of each thing do I print?" Answer that, and the loop bounds write themselves.

(Suggested image: all five patterns in one shareable graphic with the loop condition beside each — this is prime Pinterest/exam-season content and targets the huge "pattern programs in C" keyword family)


break and continue in Nested Loops: The Rules

From our jump-statement pages — both statements affect only the loop they physically sit in:

main.c
Run Online
for (int i = 1;
i <= 3;
i++) {
    for (int j = 1;
    j <= 5;
    j++) {
        if (j == 3) break;
        // kills inner loop at j=3, every row        printf("[%d,%d] ", i, j);
    }
    printf("\n");
}
main.c
Run Online
[1,1] [1,2][2,1] [2,2][3,1] [3,2]

The inner loop dies mid-row, the outer loop keeps marching. Escaping BOTH loops needs a flag (or the disciplined goto from last page):

main.c
Run Online
int found = 0;
for (int i = 0;
i < rows && !found;
i++) {
    for (int j = 0;
    j < cols;
    j++) {
        if (matrix[i][j] == target) {
            printf("Found at [%d][%d]\n", i, j);
            found = 1;
            break;
            // exits inner;
            outer sees !found fail
        }
    }
}

Real Work: A Multiplication Table Grid

main.c
Run Online
#include <stdio.h>
int main() {
    int size = 10;
    printf("    ");
    for (int h = 1; h <= size; h++) {
        printf("%4d", h);
        // header row
    }
    printf("\n");
    for (int row = 1; row <= size; row++) {
        printf("%4d", row);
        // row label
        for (int col = 1; col <= size; col++) {
            printf("%4d", row * col);
        }
        printf("\n");
    }
    return 0;
}

Output (truncated):

main.c
Run Online
1 2 3 4 5 ...
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
...

A 10×10 grid = 100 products from six lines of loop code — plus the %4d width formatting from our printf tutorial keeping every column aligned. This is nested loops earning their keep.


A Word About Cost: Nested Loops Get Expensive Fast

Here's the practical warning that matters in real programs: nested loops multiply work.

  • 1 loop over 1,000 items → 1,000 operations
  • 2 nested loops → 1,000 × 1,000 = 1,000,000 operations
  • 3 nested loops → a billion

For patterns and small grids, irrelevant. For large datasets, the difference between a program that finishes and one that "hangs" is often one nesting level too many. (This idea has a formal name — time complexity — and you'll meet it properly when you study data structures. For now, just respect the multiplication.)


The Six Classic Nested-Loop Mistakes

  1. Reusing the same counter in both loops —
    main.c
    Run Online
    for (int i = 0; i < 3; i++) {
        for (int i = 0; i < 3; i++) {
            ...
        }
        // inner shadows outer — chaos
    }
    Use i/j/k (or better: row/col) — never the same name.
  2. Forgetting the inner loop restarts — expecting j to keep its value across outer iterations. It's re-initialized every pass; design around that.
  3. Misplacing the newline or summary code — printf("\n") inside the inner loop breaks the grid; it belongs between the loops. When output "explodes" into one-per-line, check where your newline lives.
  4. Inner condition depending on the wrong variable — j <= i vs j <= n produce completely different patterns. When a pattern comes out sideways, the inner bound is suspect #1.
  5. Expecting break to exit both loops — it exits one. Flag or goto for multi-level escapes.
  6. Deep nesting (3+ levels) without a strong reason — readability and performance both collapse. If you're four levels deep, stop and rethink the approach.

(Suggested image: "6 Nested Loop Mistakes" checklist graphic — consistent with the series)


Final Thoughts

Nested loops mark a genuine level-up: you stop thinking about a repetition and start thinking about relationships between repetitions — rows to columns, sets to reps, patterns to positions. Master the one rule (inner completes fully per outer pass), learn to derive patterns from the row-number question, and respect the multiplication of work, and you've gained a tool that quietly powers everything from matrix math to game boards to image processing.

This also closes the loop (sorry) on control flow in C. Every decision structure, every loop, every jump — you have the complete set. Next, we change gears entirely and look at the data these structures operate on: data types and variables.

Runnable C Code Example & Practical Implementation

main.c
Run Online
#include <stdio.h>
int main() {
    printf("Multiplication Table (1 to 4):\
");
    for (int row = 1; row <= 4; row++) {
        for (int col = 1; col <= 4; col++) {
            printf("%4d", row * col);
        }
        printf("\
");
    }
    return 0;
}

Key Takeaways, Best Practices & Memory Safety Rules

Best Practice & Key Takeaways
Always iterate multi-dimensional arrays in row-major order ([row][col]) to maximize CPU L1/L2 cache spatial locality.

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked C programming interview questions
Q

Q: What is the danger of accidentally using the same index variable `i` in both outer and inner loops?

A: The inner loop modifies `i`, corrupting the outer loop's counter and typically causing premature termination or an infinite loop.
Q

Q: How do cache lines affect nested loop traversal speed in C?

A: In C (row-major order), iterating row-by-row `[i][j]` accesses contiguous memory and is drastically faster than column-by-column `[j][i]` due to CPU cache hits.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations