Multi-dimensional and jagged arrays
Store tables and grids with 2D arrays, rows of different lengths with jagged arrays, and loop through both.
Rectangular (2D) arrays: int[,]
int[,] grid = new int[3, 4]; // 3 rows, 4 columns, all 0 int[,] seats ={ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }}; Console.WriteLine(seats[1, 2]); // row 1, column 2 → 7seats[0, 0] = 100;Console.WriteLine(seats.GetLength(0)); // rows: 3Console.WriteLine(seats.GetLength(1)); // columns: 4Console.WriteLine(seats.Length); // all cells: 127 3 4 12
Looping through a 2D array
int[,] sales ={ { 5, 3, 8 }, // shop 0: Mon, Tue, Wed { 2, 7, 4 }, // shop 1}; for (int r = 0; r < sales.GetLength(0); r++){ int rowTotal = 0; for (int c = 0; c < sales.GetLength(1); c++) { rowTotal += sales[r, c]; } Console.WriteLine($"Shop {r}: {rowTotal}");}Shop 0: 16 Shop 1: 13
Jagged arrays: int[][]
int[][] rooms = new int[3][]; // 3 rows, not created yet (null)rooms[0] = new int[] { 101, 102 };rooms[1] = new int[] { 201, 202, 203, 204 };rooms[2] = new int[] { 301 }; Console.WriteLine(rooms[1][3]); // 204 (note: [row][col])Console.WriteLine(rooms.Length); // 3 rowsConsole.WriteLine(rooms[1].Length); // 4 in row 1 foreach (int[] floor in rooms){ Console.WriteLine(string.Join(" ", floor));}204 3 4 101 102 201 202 203 204 301
| 2D array `int[,]` | Jagged array `int[][]` | |
|---|---|---|
a[r, c] | a[r][c] | |
GetLength(0) / GetLength(1) | a.Length / a[r].Length | |
A matrix example
int size = 3;double[,] identity = new double[size, size];for (int i = 0; i < size; i++) identity[i, i] = 1; // 1 on the diagonal, 0 elsewhere for (int r = 0; r < size; r++){ for (int c = 0; c < size; c++) Console.Write(identity[r, c] + " "); Console.WriteLine();}1 0 0 0 1 0 0 0 1
int[,] with the values 1 to 9 and print the sum of the main diagonal (top-left to bottom-right) and the sum of each column.
Show the solution
int[,] m ={ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }}; int diagonal = 0;for (int i = 0; i < 3; i++) diagonal += m[i, i];Console.WriteLine($"Diagonal: {diagonal}"); for (int c = 0; c < m.GetLength(1); c++){ int colSum = 0; for (int r = 0; r < m.GetLength(0); r++) colSum += m[r, c]; Console.WriteLine($"Column {c}: {colSum}");}Diagonal: 15 Column 0: 12 Column 1: 15 Column 2: 18
Remember
int[,]is a rectangular grid accessed witha[row, col].GetLength(0)= rows,GetLength(1)= columns,Length= all cells.int[][]is an array of arrays; each row can be a different length.Use nested loops: outer over rows, inner over columns.