C++ ยท Chapter 21 of 49

C++ Multidimensional Arrays

A 2D array is declared as `type name[rows][cols]` and can be visualised as a grid or table. It's stored as one contiguous block of memory in row-major order.

Nested loops are the standard way to fill and traverse multidimensional arrays, using one loop variable per dimension.

Declaring a 2D array

`int grid[2][3] = {{1,2,3},{4,5,6}};` creates a 2-row, 3-column array. Access an element with `grid[row][col]`.

Traversing with nested loops

An outer loop typically walks rows while an inner loop walks columns, printing or summing every element in the grid.

Example 1 (cpp)
int grid[2][2] = {{1,2},{3,4}};
std::cout << grid[1][0];
Output
3

grid[1][0] accesses row 1, column 0.

Example 2 (cpp)
int grid[2][2] = {{1,2},{3,4}};
for (int i=0;i<2;i++)
  for (int j=0;j<2;j++)
    std::cout << grid[i][j];
Output
1234

Nested loops visit every cell in row-major order.

Key points

  • 2D arrays are declared as type name[rows][cols].
  • Access elements with arr[row][col].
  • Stored contiguously in row-major order.
  • Nested loops are used to fill/traverse them.
๐Ÿ’ก Note: For dynamic sizes, prefer std::vector<std::vector<int>> over raw 2D arrays.

๐Ÿ“ Quick Quiz

1. How do you access row 2, column 1 of grid?

2. 2D arrays are stored in memory as:

3. How many loops are typically used to traverse a 2D array?