Use of nested for loops involves creating complex, variable-bound patterns, efficiently processing multi-dimensional data structures like matrices, and understanding techniques for controlling the flow across multiple loop levels.
Uses of Nested for Loops in C 🔢
While a basic nested loop creates a simple grid, its applications are key to solving more complex problems in algorithms and data manipulation.
1. Generating Complex Patterns
The key to creating non-rectangular patterns (like triangles or pyramids) is to make the inner loop's condition dependent on the outer loop's variable.
Example: Printing a Number Pyramid
The outer loop controls the rows. The inner loop, which prints the numbers, runs i times, where i is the current row number.
C
#include <stdio.h>
int main() {
int rows = 5;
// Outer loop iterates through each row
for (int i = 1; i <= rows; i++) {
// Inner loop prints numbers from 1 up to the current row number 'i'
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
// Move to the next line after the row is printed
printf("\n");
}
return 0;
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
2. Processing 2D Arrays (Matrices)
Nested for loops are the standard and most efficient way to process every element in a 2D array. The outer loop typically iterates over the rows, and the inner loop iterates over the columns within each row.
Example: Matrix Transposition
Transposing a matrix means swapping its rows and columns. The element at matrix[i][j] moves to transpose[j][i].
C
#include <stdio.h>
#define ROWS 2
#define COLS 3
int main() {
int matrix[ROWS][COLS] = { {1, 2, 3}, {4, 5, 6} };
int transpose[COLS][ROWS];
// Transpose the matrix
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Print the transposed matrix
printf("Transposed Matrix:\n");
for (int i = 0; i < COLS; i++) {
for (int j = 0; j < ROWS; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Transposed Matrix:
1 4
2 5
3 6
3. Breaking Out of Nested Loops
A common challenge is that a break statement only exits the innermost loop. The cleanest way to break out of multiple loops at once is often with a goto statement.
Example: Searching in a 2D Array
This code searches a matrix for the first negative number and stops all searching as soon as it's found.
C
#include <stdio.h>
int main() {
int matrix[3][3] = { {5, 8, 2}, {9, -1, 4}, {3, 7, 6} };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] < 0) {
printf("Negative number found at (%d, %d). Stopping.\n", i, j);
goto found; // Jump out of both loops
}
}
}
found:
printf("Search complete.\n");
return 0;
}
4. Flattening Nested Loops (Optimization)
For fixed-size multi-dimensional arrays, you can sometimes improve performance by converting nested loops into a single loop. This can help the compiler's optimizer by simplifying the control flow.
- The Technique: A single loop iterates from 0 to ROWS * COLS - 1. The row and column indices are then calculated from the single loop variable using division and modulo.
- row = i / NUM_COLS;
- col = i % NUM_COLS;
Example: Single-Loop Array Initialization
C
#include <stdio.h>
#define ROWS 2
#define COLS 5
int main() {
int matrix[ROWS][COLS];
// Flattened loop to initialize the matrix
for (int k = 0; k < ROWS * COLS; k++) {
int row = k / COLS;
int col = k % COLS;
matrix[row][col] = k;
}
// Print the matrix to verify
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%2d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}