Understanding 2D and 3D Arrays in C

A beginner-friendly breakdown of how to use multidimensional arrays.

🔷 2D Array in C

A 2D array is like a matrix (rows and columns).

int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

This creates a matrix like:

[1, 2, 3]
[4, 5, 6]

🔁 Accessing 2D Array with Loops

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++) {
        printf("Element at [%d][%d] = %d\n", i, j, matrix[i][j]);
    }
}

🔷 3D Array in C

A 3D array adds another layer (depth) to the 2D structure.

int cube[2][2][3] = {
    {
        {1, 2, 3},
        {4, 5, 6}
    },
    {
        {7, 8, 9},
        {10, 11, 12}
    }
};

This can be visualized as two 2D blocks:

Block 0:
[1, 2, 3]
[4, 5, 6]

Block 1:
[7, 8, 9]
[10, 11, 12]

🔁 Accessing 3D Array with Nested Loops

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 2; j++) {
        for (int k = 0; k < 3; k++) {
            printf("Element at [%d][%d][%d] = %d\n", i, j, k, cube[i][j][k]);
        }
    }
}

📚 Use Cases