C Nested Loops

Beginner
7 min read
Updated: Nov 2026
3 examples

What Are Nested Loops?

A nested loop is a loop placed inside the body of another loop. For every single pass of the outer loop, the inner loop runs from start to finish. You can nest for, while, and do-while in any combination.

Remember
for (outer init; outer test; outer update) {
    for (inner init; inner test; inner update) {
        /* inner body */
    }
    /* runs once per outer pass, after the inner loop ends */
}

total inner-body runs = outer passes x inner passes
LayerRunsTypical job
Outer loopOnce per row / groupPick the row, line, or group
Inner loopFully, each outer passWalk the columns or items in that row
Code after inner loopOnce per outer passPrint a newline, reset totals

How to Use Nested Loops in C

Give each loop its own counter, restart the inner counter every outer pass, and decide where the newline or subtotal belongs.

  1. Choose the outer counter (for example r for rows) and the inner counter (c for columns).
  2. Declare the inner counter inside the outer body so it restarts at its initial value each time.
  3. Put per-item work (like printf("* ")) in the inner body.
  4. Put per-row work (like printf("\n")) after the inner loop, still inside the outer body.
  5. Compile with gcc file.c -std=c11 -o out and run.
PieceRequired?Role
Outer loop headerYesControls how many times the inner loop restarts
Inner loop headerYesControls work inside one outer pass
Separate countersYesReusing one variable breaks both loops
Statement between loopsOptionalNewlines, subtotals, resets

Pseudocode

Pseudocode
for each row from 0 to rows - 1:
    for each column from 0 to cols - 1:
        do the per-cell work
    do the per-row work (newline, subtotal)

// inner loop restarts from its first value for every row

Cheat Sheet

Keep these facts handy when you write loops inside loops.

TopicDetail
Total iterationsouter x inner (if the inner bound is constant)
Triangular inner boundfor (c = 0; c <= r; c++) gives about n(n+1)/2 runs
Inner counterReset automatically when declared in the inner for header
break / continueAffect only the innermost loop (see break)
Common usesGrids, tables, patterns, matrices, pair checks
Mix loop typesA for can sit inside a while, and the reverse

Worked Walkthrough — A 2 x 3 Grid

Trace for (r = 0; r < 2; r++) { for (c = 0; c < 3; c++) printf("*"); printf("\n"); } one step at a time.

Calculation
r = 0
  c = 0 -> print *
  c = 1 -> print *
  c = 2 -> print *
  c = 3 -> test fails, inner loop ends
  print newline                     row 1: ***

r = 1
  c = 0 -> print *
  c = 1 -> print *
  c = 2 -> print *
  c = 3 -> test fails, inner loop ends
  print newline                     row 2: ***

r = 2 -> test fails, outer loop ends

inner body ran 2 x 3 = 6 times

C Examples

Compile with gcc file.c -std=c11 -o out. Compare with the single-loop forms in for and while.

Example 1 — Print a 3 x 4 Grid of Stars

The classic first nested loop: rows on the outside, columns on the inside.

C
#include <stdio.h>
      
      int main(void) {
          int rows = 3;
          int cols = 4;
      
          for (int r = 0; r < rows; r++) {
              for (int c = 0; c < cols; c++) {
                  printf("* ");
              }
              printf("\n");
          }
      
          return 0;
      }

How It Works

  1. Outer loop picks the row. r goes 0, 1, 2.
  2. Inner loop fills the row. c restarts at 0 and prints four stars.
  3. Newline after the inner loop. It runs once per row, not once per star.
  4. Total. 3 x 4 = 12 stars are printed.

Example 2 — Print a 3 x 3 Multiplication Grid

Both counters take part in the calculation, so each cell is i * j.

C
#include <stdio.h>
      
      int main(void) {
          for (int i = 1; i <= 3; i++) {
              for (int j = 1; j <= 3; j++) {
                  printf("%4d", i * j);
              }
              printf("\n");
          }
      
          return 0;
      }

How It Works

  1. Row number is i. It stays fixed while the inner loop runs.
  2. Column number is j. It cycles 1 to 3 for every row.
  3. Width helps alignment. %4d pads each product to four characters.
  4. Newline per row. Placed after the inner loop.

Example 3 — break Leaves Only the Inner Loop

A break inside a nested loop stops the innermost loop only; the outer loop keeps going.

C
#include <stdio.h>
      
      int main(void) {
          for (int i = 1; i <= 3; i++) {
              for (int j = 1; j <= 3; j++) {
                  if (j == 2) {
                      break;
                  }
                  printf("(%d,%d) ", i, j);
              }
              printf("\n");
          }
      
          return 0;
      }

How It Works

  1. Inner pass 1. j = 1 prints (i,1).
  2. Inner pass 2. j == 2 triggers break; the inner loop ends early.
  3. Outer loop continues. The newline prints, then i increases.
  4. Takeaway. To leave both loops, use a flag or return.

Edge Cases & Pitfalls

Check these before shipping loops inside loops.

counter

Reusing the same variable

If both loops use i, the inner loop changes the outer counter and the loops misbehave or never end. Use r/c or i/j.

reset

Forgetting to reset the inner counter

With a while inner loop, set c = 0 inside the outer body. Declared once outside, c stays at its last value and later rows print nothing.

placement

Newline in the wrong spot

Put printf("\n") after the inner loop. Inside it, every cell gets its own line.

exit

break only leaves one loop

Use a flag checked by the outer loop, a goto with care, or move the loops into a function and return.

cost

Quadratic growth

Doubling both bounds quadruples the work. Three levels grow cubically, so avoid deep nesting on large inputs.

Performance Notes

ShapeIterationsTypical use
Two loops, bounds n and mn x mGrids, matrices, tables
Inner bound grows with outerAbout n(n+1)/2Triangles, pairs (i, j) with j <= i
Three nested loopsn x m x k3D data, matrix multiply

Nested loops multiply iteration counts, so the innermost body dominates run time. Keep it small and move work that does not depend on the inner counter out of the inner loop. See for for counted loop basics.

Key Takeaways

  • Role: a loop inside a loop; the inner one runs fully for each outer pass.
  • Count: total body runs equal outer passes times inner passes.
  • Counters: give each loop its own variable and restart the inner one each row.
  • Exit: break and continue affect only the innermost loop.

One line: outer loop picks the row, inner loop walks the columns.

Frequently Asked Questions

A nested loop is a loop inside another loop's body. The inner loop completes all its iterations for each single iteration of the outer loop.
Once per outer iteration, so the inner body runs outer x inner times in total when the inner bound is constant.
Yes. Any loop type can be nested in any other. Pick the form that matches each level's role (counted, condition-based, or at-least-once).
No. break leaves only the innermost loop containing it. Use a flag, return from a function, or goto to leave several levels.
A for loop resets it through its init clause. With while loops you must set the counter to its starting value inside the outer body, or later rows will skip the inner loop.
Make the inner bound depend on the outer counter, for example for (c = 0; c <= r; c++). Row r then prints r + 1 items.

Next: C Math

Explore math functions and numeric helpers in C.

C Math tutorials →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful