Multidimensional arrays
Learn multidimensional arrays as matrices with int[,].
Multidimensional arrays
For row-and-column data you use a multidimensional array. The most common type is int[,], which represents a two-dimensional matrix: int[,] m = { { 1, 2 }, { 3, 4 } };.
Access uses two indices: m[0, 1] gives the first row's second column. m.GetLength(0) returns the row count and m.GetLength(1) the column count. Nested for loops walk every cell.
Walking a matrix with nested for
To walk every cell of a matrix you use two nested for loops. The outer loop walks rows, the inner loop walks columns: for (int i = 0; i < m.GetLength(0); i++) for (int j = 0; j < m.GetLength(1); j++) ... m[i, j] ....
This pattern suits walking student grades in a class or a chess board. The inner loop restarts on each row; so each (i, j) pair is visited exactly once.
Exercise Declare a matrix and print a cell
Declare a matrix m with the value { { 1, 2, 3 }, { 4, 5, 6 } } (two rows, three columns). Then print m[1, 2] with Console.WriteLine. The output should be 6.
Show example solution
Write int[,] m = { { 1, 2, 3 }, { 4, 5, 6 } }; and print it with Console.WriteLine(m[1, 2]);
Example solution:
using System;
class Program
{
static void Main()
{
int[,] m = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine(m[1, 2]);
}
}
Test yourself
-
How many elements does int[,] m = new int[2, 3]; have?
int[,] m = new int[2, 3]; Console.WriteLine(m.Length);- 6
- 5
- 3
- 2
Show answer
6 — Correct. 2 rows × 3 columns = 6 cells.
-
Match each matrix part to its meaning
- int[,]
- Two-dimensional array
- GetLength(0)
- Row count
- GetLength(1)
- Column count
- m[1, 2]
- Specific cell
-
Write the matrix cell index
int[,] m = new int[2, 3]; int v = m[____, 2];Show answer
int[,] m = new int[2, 3]; int v = m[1, 2];