C Nested Loops
Introduction to Nested Loops
Nested loops occur when one loop is placed inside another loop. This powerful technique allows you to work with multi-dimensional data structures, perform complex iterations, and solve problems that require multiple levels of repetition.
The inner loop completes all its iterations for each iteration of the outer loop, creating a multiplicative effect on the total number of iterations.
Basic Nested Loop Structure
The most common form of nested loops is a for loop inside another for loop:
for (initialization; condition; increment) { // Outer loop
for (initialization; condition; increment) { // Inner loop
// Code to execute
}
}
The inner loop runs to completion for each iteration of the outer loop.
Basic Example
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
printf("i=%d j=%d\n", i, j);
}
}
return 0;
}
i=1 j=1 i=1 j=2 i=2 j=1 i=2 j=2 i=3 j=1 i=3 j=2
Pattern Printing with Nested Loops
Nested loops are commonly used to print patterns like triangles, rectangles, and other shapes.
#include <stdio.h>
int main(void) {
int rows = 5;
// Right triangle
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
// Rectangle 4 x 6
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 6; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Multiplication Table Example
Nested loops are perfect for generating multiplication tables and other grid-based data.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
printf("%4d", i * j);
}
printf("\n");
}
return 0;
}
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
2D Array Processing
Nested loops are essential for working with two-dimensional arrays, as they allow you to access each element by its row and column indices.
#include <stdio.h>
int main(void) {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12
Different Types of Nested Loops
You can nest different types of loops together, such as for loops inside while loops, or do-while loops inside for loops.
#include <stdio.h>
int main(void) {
int i = 1;
while (i <= 2) {
for (int j = 1; j <= 2; j++) {
printf("i=%d j=%d\n", i, j);
}
i++;
}
for (int x = 1; x <= 2; x++) {
int y = 1;
do {
printf("x=%d y=%d\n", x, y);
y++;
} while (y <= 2);
}
return 0;
}
i=1 j=1 i=1 j=2 i=2 j=1 i=2 j=2 x=1 y=1 x=1 y=2 x=2 y=1 x=2 y=2
Early Exit From Nested Loops
In C, break only exits the innermost loop. To stop outer loops early, use a flag (or, less commonly, a goto label).
#include <stdio.h>
#define ROWS 3
#define COLS 4
int main(void) {
int matrix[ROWS][COLS] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int target = 7;
int found = 0;
for (int r = 0; r < ROWS && !found; r++) {
for (int c = 0; c < COLS; c++) {
if (matrix[r][c] == target) {
printf("Found %d at r=%d c=%d\n", target, r, c);
found = 1;
break; // exits inner loop only
}
}
}
if (!found) {
printf("%d not found\n", target);
}
return 0;
}
Found 7 at r=1 c=2
Performance Considerations
Nested loops can significantly impact performance, especially with large iteration counts:
• Total iterations = (outer iterations) × (inner iterations) [× (next inner) …]
• Three nested loops with 100 iterations each execute 1,000,000 times
• Consider algorithmic complexity (e.g., O(N×M)) and move invariant work outside inner loops when possible
• Avoid heavy I/O inside inner loops; it becomes a major bottleneck
Best Practices
1. Use meaningful names for loop counters (e.g., row/col instead of i/j when appropriate)
2. Keep nesting depth reasonable—deeply nested loops can be hard to understand
3. Extract complex inner-loop logic into helper functions to improve readability
4. Be mindful of performance with large iteration counts
5. Use consistent indentation to make the nesting structure clear
6. Add comments to explain the purpose of each loop level