Lesson 24 +10 XP

Multidimensional Arrays

Multidimensional Arrays

Sometimes data is naturally a grid - like a spreadsheet or a chessboard. C# has two flavors for this: multidimensional and jagged arrays.

Multidimensional arrays

Declare with extra commas - one comma for a 2D array:

int[,] numbers = { { 1, 4, 2 }, { 3, 6, 8 } };

This is a 2x3 grid:

1 4 2
3 6 8

Access with two indexes:

Console.WriteLine(numbers[0, 2]);   // 2 (row 0, column 2)

Change an element:

numbers[1, 1] = 5;   // the 6 becomes 5

Loop through a 2D array

int[,] numbers = { { 1, 4, 2 }, { 3, 6, 8 } };

for (int i = 0; i < numbers.GetLength(0); i++)
{
  for (int j = 0; j < numbers.GetLength(1); j++)
  {
    Console.WriteLine(numbers[i, j]);
  }
}

GetLength(0) gives the number of rows; GetLength(1) gives the columns.

Jagged arrays

A jagged array is an array of arrays, where each row can have a different length:

int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };

TL;DR

  • 2D arrays use [,] and need two indexes.
  • GetLength(0) / GetLength(1) give dimensions.
  • Jagged arrays are arrays of arrays with variable row lengths.