0
0
CHow-ToBeginner · 3 min read

How to Write Nested For Loop in C: Syntax and Example

In C, a nested for loop is a for loop inside another for loop, written using for statements one inside the other. The outer loop runs first, and for each iteration, the inner loop runs completely, allowing you to repeat actions in a grid or matrix style.
📐

Syntax

A nested for loop in C uses one for loop inside another. The outer loop controls the number of times the inner loop runs. Each loop has three parts: initialization, condition, and update.

  • Initialization: sets the starting point.
  • Condition: keeps the loop running while true.
  • Update: changes the loop variable each time.
c
for (int i = 0; i < outer_limit; i++) {
    for (int j = 0; j < inner_limit; j++) {
        // code to repeat
    }
}
💻

Example

This example prints a 3x3 grid of numbers showing the current row and column indexes using nested for loops.

c
#include <stdio.h>

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            printf("%d,%d ", i, j);
        }
        printf("\n");
    }
    return 0;
}
Output
1,1 1,2 1,3 2,1 2,2 2,3 3,1 3,2 3,3
⚠️

Common Pitfalls

Common mistakes include:

  • Using the same loop variable name in both loops, which causes errors.
  • Forgetting to update the loop variable, causing infinite loops.
  • Incorrect loop conditions that skip or overrun iterations.

Always use different variable names for each loop and check your loop conditions carefully.

c
/* Wrong: same variable 'i' used in both loops */
for (int i = 0; i < 3; i++) {
    for (int i = 0; i < 3; i++) {
        // This causes logic errors
    }
}

/* Correct: different variables 'i' and 'j' */
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        // Correct nested loop
    }
}
📊

Quick Reference

  • Use different variable names for each loop.
  • Outer loop runs first; inner loop runs completely each time.
  • Initialization, condition, and update are required in each for loop.
  • Nested loops are useful for working with grids, tables, or multi-dimensional data.

Key Takeaways

A nested for loop is a loop inside another loop, each with its own variable.
Use different variable names for outer and inner loops to avoid conflicts.
The inner loop runs fully for each iteration of the outer loop.
Nested loops are great for handling multi-dimensional data like grids.
Always check loop conditions to prevent infinite loops or skipped iterations.