0
0
Cprogramming~5 mins

Nested loops in C

Choose your learning style9 modes available
Introduction

Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.

Printing a multiplication table.
Going through rows and columns in a grid.
Checking every pair of items in a list.
Creating patterns with stars or numbers.
Syntax
C
for (initialization; condition; update) {
    for (initialization; condition; update) {
        // code to repeat
    }
}
The inner loop runs completely every time the outer loop runs once.
You can use other loops like while or do-while inside each other too.
Examples
This prints pairs of numbers where i goes from 1 to 3 and j goes from 1 to 2.
C
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        printf("%d %d\n", i, j);
    }
}
Using while loops nested to print pairs of numbers.
C
int i = 1;
while (i <= 2) {
    int j = 1;
    while (j <= 3) {
        printf("%d %d\n", i, j);
        j++;
    }
    i++;
}
Sample Program

This program prints a rectangle of stars with 3 rows and 4 columns using nested for loops.

C
#include <stdio.h>

int main() {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 4; col++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
OutputSuccess
Important Notes

Be careful with loop limits to avoid infinite loops.

Indent your code inside loops to keep it clear.

Summary

Nested loops run one loop inside another to repeat actions in layers.

They are useful for working with tables, grids, or pairs of data.

Always check your loop conditions to avoid mistakes.