2.3.7 Rows and Columns in Two-Dimensional Arrays

Read Team Rows Before Round Columns

Before accessing a two-dimensional score, decide what each dimension means. Here row 0 represents the Wildcats, row 1 represents a visiting team, and columns 0 through 2 represent three training rounds.

That convention makes every index pair interpretable. It is part of the application model; C# itself does not know what a team or round means.

Read the Soccer Grid First
Goals by team and round
Team row Round column 0 Round column 1 Round column 2
0: Wildcats 2 0 3
1: Visiting team 1 4 2

To find the visiting team's first-round score, choose row 1 and column 0. Moving to row 0 instead would select the Wildcats, even if the score happened to be the same in another example.

Connect the Grid with C#
Select a row and then a column
int[,] teamGoals = { { 2, 0, 3 }, { 1, 4, 2 } };
int visitingFirstRound = teamGoals[1, 0];
int wildcatsThirdRound = teamGoals[0, 2];
int teamCount = teamGoals.GetLength(0);
int roundCount = teamGoals.GetLength(1);
int scoreCount = teamGoals.Length;

The initializer groups the rows

The first inner group contains row 0: 2, 0, 3. The next group contains row 1: 1, 4, 2. Each row has three columns, producing one rectangular array.

The two selected reads copy 1 into visitingFirstRound and 3 into wildcatsThirdRound. Reading those scores does not change the array.

Ask for the count of a particular dimension

teamGoals.GetLength(0) returns 2, the number of team rows. teamGoals.GetLength(1) returns 3, the number of round columns.

The argument to GetLength identifies a dimension. It is not a row or column position whose score you want to read.

Explain a Selected Score

What score does teamGoals[1, 1] read? How many total elements would an array with three teams and four rounds contain?

Solution

The read produces 4: visiting-team row 1, round column 1. A three-by-four array has 12 elements, with three valid row positions and four valid column positions.

Use the Original Diagram to Check Your Reasoning

The diagram below shows the original example. Compare it with your prediction for the requested change; its pictured values have not been replaced by the practice inputs.

Rows identify teams and columns identify rounds. Pair [1,0] contains 1 and pair [0,2] contains 3.
Pairs select the score positions
  • New
  • Changed
  • Removed

The first number in each pair identifies the team row. The second identifies the round column. The values match the earlier table and the C# initializer.