Nested Loops in C Explained

A nested loop is a loop inside another loop structure. In C language, the nested loop operates in such a way that every time the outer loop runs, the inner loop completes a full iteration.

The following code demonstrates a simple nested loop:

#include <stdio.h>

int main() {
    int i, j;

    for(i = 1; i <= 3; i++) {
        for(j = 1; j <= 3; j++) {
            printf("%d %d\n", i, j);
        }
    }

    return 0;
}

In the above code, the outer loop for(i = 1; i <= 3; i++) will run 3 times, and each time the inner loop for(j = 1; j <= 3; j++) will complete 3 iterations. As a result, the program will output the following content:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

In C language, the inner loop completes a full cycle in each iteration of the outer loop until the outer loop finishes executing. This is how nested loops in C language work.

bannerAds