Course contentsShow
← C
Lesson 411 of 1,2196. Arrays and StringsFree lesson

Nested `for` loops for 2D traversal

Nested for loops for 2D traversal

What you'll learn: How to use one loop inside another to systematically visit every single "cell" in a two-dimensional array.

The Grid Walk

In the previous lesson, we learned that a 2D array is essentially a grid of rows and columns. To work with this grid in code, we need a way to visit every spot without getting lost. Imagine you are mowing a rectangular lawn: you walk from left to right across the first row, turn around, move down one step, and then walk across the second row.

In C, we replicate this movement using nested loops. The "outer" loop controls which row we are currently standing on, and the "inner" loop controls which column (or seat) we are looking at within that specific row.

How it works in code

Think of the outer loop as the "Hour" hand and the inner loop as the "Minute" hand. The minute hand must complete a full circle before the hour hand clicks forward by one.

In the example below, we have a grid with 3 rows and 4 columns. Notice how the inner loop (j) runs through its entire cycle for every single increment of the outer loop (i).

#include <stdio.h>

int main() {
    // A 2D array with 3 rows and 4 columns
    int grid[3][4] = {
        {10, 11, 12, 13},
        {20, 21, 22, 23},
        {30, 31, 32, 33}
    };

    // Outer loop: iterates through each row
    for (int i = 0; i < 3; i++) {
        
        // Inner loop: iterates through each column in the current row
        for (int j = 0; j < 4; j++) {
            printf("%d ", grid[i][j]);
        }
        
        // After finishing one row, print a newline to move to the next
        printf("\n");
    }

    return 0;
}

Why the order matters

By convention, we use i for rows and j for columns. When the code runs grid[i][j], it is saying: "Go to row i, then find item j."

If you swapped the loops, you would be walking down the columns first (top-to-bottom) instead of across the rows (left-to-right). While both methods visit every cell, row-major order (across the rows) is the standard way C organizes data in memory, making this specific nesting pattern the most efficient way to handle 2D data.

Key takeaway

To traverse a 2D array, use an outer loop for the rows and an inner loop for the columns to access each element at array[row][col].