C Nested Loops: Understanding Inner and Outer Loops

Explore the concept of nested loops in C programming, where a loop is placed inside another loop. Learn how the "inner loop" executes for each iteration of the "outer loop," allowing for more complex iterations and data processing in your programs. Discover practical examples and applications of nested loops to enhance your coding skills.



C Nested Loops

Nested Loops

It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Syntax

int i, j;

// Outer loop
for (i = 1; i <= 2; ++i) {
    printf("Outer: %d\n", i);  // Executes 2 times

    // Inner loop
    for (j = 1; j <= 3; ++j) {
        printf(" Inner: %d\n", j);  // Executes 6 times (2 * 3)
    }
}
Output

Outer: 1
 Inner: 1
 Inner: 2
 Inner: 3
Outer: 2
 Inner: 1
 Inner: 2
 Inner: 3