04. Nested Loops & 2D Matrix Traversal in C
🟡 Difficulty: Intermediate | Multidimensional Iteration & Row-Major Memory Cache Efficiency
📖 Definition
A nested loop consists of one loop placed entirely inside the body of another loop. For every single iteration of the outer loop, the inner loop executes through all of its iterations from start to finish.
🎯 Why It Is Used
- 2D Grid & Matrix Operations: Accessing row and column elements of 2D arrays (e.g.
matrix[row][col]). - Pattern Printing: Rendering geometric grids, triangles, and tables in console outputs.
- O(N2) Sorting Algorithms: Implementing algorithms like Bubble Sort and Selection Sort.
⚙️ How It Works: Row-Major Memory Order Optimization
In C, 2D arrays are stored in contiguous RAM in Row-Major Order (elements of Row 0 appear sequentially, followed by Row 1). Accessing 2D arrays with the outer loop bound to rows and the inner loop bound to columns matches memory layout, maximizing CPU cache line hits.
📝 Syntax
for (int row = 0; row < ROWS; row++) { // Outer Loop (Rows)
for (int col = 0; col < COLS; col++) { // Inner Loop (Columns)
// Access element matrix[row][col]
}
}
🔀 Loop Nesting Flavors
You can combine any loop types together (e.g. a for loop inside a while loop, or nested while loops).
🌱 Beginner Example: Right-Angled Star Triangle Pattern
#include <stdio.h>
int main(void) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n"); // Newline after completing each row
}
return 0;
}
🌼 Intermediate Example: 2D Matrix Multiplication & Sum
#include <stdio.h>
#define ROWS 3
#define COLS 3
int main(void) {
int matrix[ROWS][COLS] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int total_sum = 0;
printf("=== 2D Matrix Elements ===\n");
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
printf("%3d ", matrix[r][c]);
total_sum += matrix[r][c];
}
printf("\n");
}
printf("Sum of all 2D Matrix Elements: %d\n", total_sum);
return 0;
}
🌲 Advanced Example: Cache-Friendly Row-Major vs Column-Major Benchmarking Concept
#include <stdio.h>
#define N 4
int main(void) {
int grid[N][N];
// Initialize 2D grid in cache-friendly Row-Major order
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
grid[i][j] = (i + 1) * 10 + (j + 1);
}
}
// Print Transposed Matrix
printf("=== Transposed Matrix View ===\n");
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
printf("%3d ", grid[r][c]);
}
printf("\n");
}
return 0;
}
🔍 Line-by-Line Explanation
for (int r = 0; r < ROWS; r++): Outer loop iterates over matrix row indices.for (int c = 0; c < COLS; c++): Inner loop iterates through every column in the current row.printf("\n");: Placed after the inner loop finishes a row to format the 2D matrix on terminal screen.
💻 Expected Terminal Output
*
* *
* * *
* * * *
* * * * *
=== 2D Matrix Elements ===
1 2 3
4 5 6
7 8 9
Sum of all 2D Matrix Elements: 45
=== Transposed Matrix View ===
11 21 31 41
12 22 32 42
13 23 33 43
14 24 34 44
⚠️ Common Mistakes & Pitfalls
- Reusing Loop Index Variable: Accidental re-use of counter variable
iin both inner and outer loops (e.g.for(i=0...) { for(i=0...) }) corrupts the outer loop counter, causing an infinite loop. - Cache Line Inefficiency (Column-Major Traversal): Swapping outer and inner loop order on huge 2D arrays degrades memory performance by jumping across cache lines.
📌 Important Rules & Limitations
- Always use distinct counter variable names for inner and outer loops (e.g.
iandj, orrowandcol). - Traverse 2D arrays in Row-Major order (row index outer, col index inner) for maximum performance.
🌐 Multilingual Explanation: English
A nested loop executes an inner loop completely for each single pass of an outer loop. Always traverse 2D arrays using row-major order (rows outer, columns inner) to match C's memory layout.
🌐 Multilingual Explanation: Hindi (Roman Script)
Nested loop mein outer loop ke har 1 turn ke liye inner loop poora chalta hai. 2D arrays ko traverse karte waqt outer loop rows ke liye aur inner loop columns ke liye rakhein.
🌐 Multilingual Explanation: Marathi (Roman Script)
Nested loop madhye outer loop chya pratyek 1 cycle sathi inner loop purna chaalto. 2D arrays print kiva process karnyasathi nested loops vapartat.
❓ Practice Questions
- If an outer loop runs 5 times and an inner loop runs 4 times, how many total times will the inner loop body execute?
- Why is row-major traversal faster than column-major traversal in C?
- What happens if you accidentally use the variable
ifor both inner and outer loops?
🚀 Practical Coding Challenge
Write a C program named multiplication_grid.c that uses nested for loops to print a formatted 10x10 multiplication grid with aligned columns.
🧭 Navigation & Breadcrumbs
← Previous: 03. Do-While Loop | Module 07 Guide | Next: 05. Break & Continue →