C# Multidimensional Arrays

Multidimensional arrays are arrays of arrays, allowing you to store data in a tabular form (rows and columns). In C#, multidimensional arrays can have two or more dimensions.

Key Topics

1. Declaring Multidimensional Arrays

Example: Creating a 2D Array

int[,] matrix = new int[2, 3];

// Initializing the array
matrix[0, 0] = 1;
matrix[0, 1] = 2;
matrix[0, 2] = 3;
matrix[1, 0] = 4;
matrix[1, 1] = 5;
matrix[1, 2] = 6;

2. Accessing Elements

Example: Reading an Element

Console.WriteLine("Element at [0,1]: " + matrix[0, 1]);  // Outputs 2

3. Looping Through Multidimensional Arrays

Example: Iterating Over a 2D Array

Console.WriteLine("Matrix Elements:");
for (int i = 0; i < matrix.GetLength(0); i++)
{
    for (int j = 0; j < matrix.GetLength(1); j++)
    {
        Console.Write(matrix[i, j] + " ");
    }
    Console.WriteLine();
}

Output:

Matrix Elements:
1 2 3
4 5 6

Key Takeaways

  • Multidimensional arrays store data in tabular form.
  • Elements are accessed using multiple indices.
  • GetLength(dimension) method retrieves the size of a dimension.
  • Nested loops are commonly used to traverse multidimensional arrays.