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

Printing a 2D matrix to the console

Printing a 2D matrix to the console

What you'll learn: How to use nested loops to display the contents of a 2D array in a clean, grid-like format.

The Grid Logic

Think of a 2D array like a spreadsheet or a bar of chocolate divided into squares. To print it so it actually looks like a grid, you need to tell the computer to visit every "room" in a building, floor by floor.

Because we have two dimensions (rows and columns), a single loop isn't enough. We use a nested loop: an outer loop that handles the rows and an inner loop that handles the individual columns within those rows.

The Nested Loop Pattern

The outer loop starts at row 0. Before it moves to row 1, the inner loop must finish running through every column in that first row. Once the inner loop hits the end of the line, we print a "newline" character (\n) to physically drop the cursor down to the next line on your screen.

Here is how you translate that into C code:

#include <stdio.h>

int main() {
    // A 3x3 matrix (3 rows, 3 columns)
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    // 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 < 3; j++) {
            printf("%d ", matrix[i][j]); // Print the number and a space
        }
        
        // After the inner loop finishes a row, move to a new line
        printf("\n");
    }

    return 0;
}

Why the formatting matters

In the code above, the printf("%d ", matrix[i][j]) inside the inner loop is the workhorse. The space after %d ensures the numbers don't bunch up like "123".

Crucially, the printf("\n") sits outside the inner loop but inside the outer loop. If you forget this, your matrix will print as one long, confusing string of numbers. By adding that newline only after the column loop completes, you create the visual "box" shape that makes data easy for humans to read.

Key takeaway

To print a 2D array, use an outer loop for rows and an inner loop for columns, ensuring you print a newline \n after each row finishes.