Back to course

Multidimensional Arrays (2D Arrays)

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 29: Multidimensional Arrays (2D Arrays)

Multidimensional arrays are arrays of arrays. The most common is the 2D array, often used to represent tables, grids, or matrices.

Declaration and Initialization

A 2D array requires two size dimensions: rows and columns.

Syntax: data_type array_name[rows][columns];

c // Array representing a 3x4 matrix int matrix[3][4];

// Initialization (grouped by row) int numbers[2][3] = { {1, 2, 3}, // Row 0 {4, 5, 6} // Row 1 };

Accessing Elements

Elements are accessed using two indices: array_name[row_index][column_index].

c // Accessing element at row 1, column 0 (which is the value 4) int value = numbers[1][0];

matrix[0][0] = 10; // Assigns 10 to the top-left element

Iterating with Nested Loops

Iterating over a 2D array always requires nested loops (one for rows, one for columns).

c #define ROWS 2 #define COLS 3

int main() { int grid[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}};

for (int i = 0; i < ROWS; i++) { // Outer loop: Rows
    for (int j = 0; j < COLS; j++) { // Inner loop: Columns
        printf("%d\t", grid[i][j]);
    }
    printf("\n");
}
return 0;

}

Memory Layout: Even though we visualize 2D arrays as tables, they are stored sequentially in memory, row by row (Row-Major Order).