Multidimensional Arrays
What is a Multidimensional Array?
• An array with more than one dimension.
• Example: table with rows and columns.
A multidimensional array is basically an array of arrays.
Arrays can have any number of dimensions. The most common are two-
dimensional arrays (2D).
Declaring a 2D Array
• int[,] matrix;
• [,] indicates two dimensions
Initializing with Size
• int[,] matrix = new int[2,3];
• 2 rows, 3 columns
Initializing with Values
• int[,] matrix = {{1,2,3}, {4,5,6}};
Column 0 Column 1 Column 2
Row 0 1 2 3
Row 1 4 5 6
Accessing Elements
matrix[row, column]
Example:
matrix[0,1] = 2
Column 0 Column 1 Column 2
Row 0 1 2 3
Row 1 4 5 6
Looping Through Array
• Use nested loops:
for rows
for columns
• Use GetLength() method
GetLength Method
• GetLength(0) = number of rows
• GetLength(1) = number of columns
Using foreach
• foreach(int value in matrix)
• Prints all values
• No index access
Example: Student Grades
• Compute average per student using loops
*show code