Lesson 64 +10 XP

Multidimensional Arrays

Multidimensional Arrays

An array inside an array is a 2D array, like a table with rows and columns.

Declaring a 2D array

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

That's 2 rows and 3 columns.

Accessing an element

First the row, then the column:

printf("%d\n", matrix[0][2]);   // 2 (row 0, col 2)

Looping through it

Nested loops, one per dimension:

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

Real uses

  • Tables and spreadsheets.
  • Images (rows of pixels).
  • Grids and game boards.

TL;DR

  • A 2D array is rows x columns.
  • Index as arr[row][col].
  • Loops with nested loops.
  • Great for tables and grids.