Multi-Dimensional Arrays (2D Matrices)

⚙️ C Language 🟢 Lesson 9 of 20 📅 2026 Edition
A multi-dimensional array is essentially an array of arrays — most commonly used to represent grids, tables, and matrices. The two-dimensional array is by far the most common, and this lesson covers how to declare, fill, and process one.
1Declaring a 2D Array
C Language ▶ Run Code
int matrix[3][4];   // 3 rows, 4 columns

int grid[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};   // initialized directly

Think of the first index as the row and the second as the column: grid[1][2] refers to row index 1, column index 2 — which holds the value 6 in the example above.

2Looping Through a 2D Array
C Language ▶ Run Code
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};

for (int row = 0; row < 2; row++) {
    for (int col = 0; col < 3; col++) {
        printf("%d ", grid[row][col]);
    }
    printf("\n");
}

Processing a 2D array almost always requires a nested loop — the outer loop walks through rows, the inner loop walks through the columns within each row.

3How 2D Arrays Are Stored in Memory

Even though you access a 2D array using two indices, the computer actually stores it as one single, continuous block of memory, row after row (called "row-major order"). Understanding this helps explain why grid[row][col] is really just convenient shorthand the compiler translates into a single calculated memory address behind the scenes.

4A Practical Example: Summing a Matrix
C Language ▶ Run Code
int matrix[2][2] = {{4, 7}, {2, 5}};
int total = 0;

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 2; j++) {
        total += matrix[i][j];
    }
}

printf("Total: %d\n", total);  // 18
⚠️ Common Mistake: Mixing Up Row and Column Order

Writing grid[col][row] instead of grid[row][col] is an easy mistake that either crashes your program (if it goes out of bounds) or, worse, quietly reads the wrong values without any error at all. Always be deliberate about which index represents rows and which represents columns, and stay consistent throughout your program.

💻 Try It Yourself

Create a 3x3 matrix of your choice, then write nested loops to calculate and print the sum of all its elements.

C Language ▶ Run Code
#include <stdio.h>

int main() {
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int total = 0;

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            total += matrix[i][j];
        }
    }

    printf("Sum of all elements: %d\n", total);
    return 0;
}
Run This in Our Compiler →