2.3.1 Two-Dimensional Arrays

Organize Soccer Scores by Team and Round

The coach now wants scores for two teams across three rounds. A single ordered line of scores no longer makes both meanings easy to see. A two-dimensional array gives each element two indexes.

For this model, the first index selects a team row and the second selects a round column. Two rows and three columns provide six int positions in one rectangular array.

Create a Rectangular Score Record
Two teams and three rounds
int[,] teamGoals = new int[2, 3];
teamGoals[1, 2] = 5;

Recognize the comma in the type

int[,] identifies a two-dimensional int array. The comma inside the type brackets distinguishes it from int[].

The creation expression new int[2, 3] requests two positions in the first dimension and three in the second. It creates six elements, all initially zero.

Use a pair of indexes for one element

The assignment teamGoals[1, 2] = 5; selects row 1 and column 2. Both indexes start at zero, so this is the second team's third-round position.

Only that one element changes. The other five elements remain zero. Assigning 5 does not create another row or column.

Inspect the Recorded State
A two by three int array has six positions. Only row 1, column 2 stores 5; the others store zero.
State after recording five goals

The indexed rows inside this diagram list all six positions of one array. They do not represent six independent arrays. The final pair [1,2] matches the pair used in the assignment.

Interpret the two dimensions
Index meaning Count Valid indexes
Team rows 2 0 and 1
Round columns 3 0, 1, and 2
Record a Different Result