2.3.1 2D Arrays

Overview

A two-dimensional array groups values by row and column. In C#, a rectangular int[,] array has a fixed number of rows and columns. Two indexes are needed to read one element. This representation suits a small grid such as seat counts in sections of an airline plane.

int[,] seats = {
    { 2, 3, 4 },
    { 5, 6, 7 }
};
int selected = seats[1, 2];
Organize Values in Two Dimensions
Organize Values in Two Dimensions. A two-dimensional array groups values by row and column.
Organize Values in Two Dimensions
  • New
  • Changed
  • Removed

The first index selects row 1 and the second selects column 2, so selected is 7. Indexes start at zero. This grid has two rows and three columns; valid row indexes are 0 and 1, and valid column indexes are 0, 1, and 2.

A rectangular array has the same number of columns in every row. Use GetLength(0) for row count and GetLength(1) for column count when you later write a traversal. Do not assume the grid is square: this example has two rows but three columns. Swapping the two indexes can select another value or exceed a boundary.

Trace the Outcome

Find seats[0,1] and seats[1,0]. Explain why seats[2,0] is invalid even though the grid has three columns. A two-dimensional array is not the same as two separate one-dimensional arrays.