C Nested Loops

A nested loop in C is a loop inside another loop. This allows you to iterate over multiple dimensions or perform more complex iterations. The inner loop runs completely for each iteration of the outer loop.

1. Nested Loop Syntax

In C, you can place a loop (either a for, while, or do-while loop) inside another loop. The outer loop runs once for each iteration of the inner loop.

Syntax:

                        
for (initialization; condition; increment) {
    for (initialization; condition; increment) {
    // Inner loop statements
    }
}
                        
                    

Example:

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

Output:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2

2. Key Points of Nested Loops

3. When to Use Nested Loops

4. Example of Nested Loops in Arrays

Nested loops are often used with multidimensional arrays. For example, a 2D array can be iterated using nested loops.

                        
#include <stdio.h>
int main() 
{
  int arr[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
        
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
        return 0;
}
                        
                    

Output:

1 2 3
4 5 6
7 8 9

5. Key Considerations

6. Nested `do-while` Loop

A nested `do-while` loop is similar to a regular `do-while` loop but can execute its statements multiple times for each iteration of the outer loop. It ensures that the loop's body executes at least once before checking the condition.

                        
#include <stdio.h>
int main() 
{
   int i = 0, j = 0;
   do {
        j = 0;
        do {
            printf("i = %d, j = %d\n", i, j);
            j++;
        } while (j < 3);
        i++;
     } while (i < 3);
     return 0;
}
                        
                    

Output:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2

7. Nested `while` Loop

A nested `while` loop is another variation where the inner loop is controlled using a `while` loop instead of a `for` loop. It can be used when you want more flexibility in controlling the number of iterations of the inner loop.

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

Output:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2