3.2.6 - Two-dimensional arrays (C#)
Store values arranged in rows and columns, then use nested loops to process the grid. Written answers use native C#. C# execution is unavailable here; the runnable activity is an optional Python demonstration.
Rows, columns and indexes
A two-dimensional array organises values using two indexes, which can represent a row and a column in a table.
Suppose two players each record scores in three rounds. Decide that rows represent players and columns represent rounds, and use that meaning consistently.
| Row index | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 0 | 4 | 7 | 5 |
| 1 | 6 | 3 | 8 |
int[,] scores = { { 4, 7, 5 }, { 6, 3, 8 } };
Console.WriteLine(scores[1, 2]);
scores[0, 1] = 9;
int[,] declares a rectangular two-dimensional array. The first displayed value is 8, because row 1 is the second player and column 2 is the third round. The assignment changes 7 to 9. Reversing the indexes is a different address, and can be outside the grid.
new int[2, 3] creates two rows and three columns, initially zero. Row indexes are 0–1 and column indexes 0–2. scores.GetLength(0) gives the number of rows, 2; scores.GetLength(1) gives the number of columns, 3. scores.Length is the total number of elements, 6, so it is not the correct row or column bound.
The assessed array scope is one and two dimensions. AQA supplied pseudocode may write scores[1][2]; native rectangular C# uses scores[1, 2].
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account