CS Multidimensional Arrays

In C#, The multidimensional array is also referred to as Rectangular arrays. It can be two or three-dimensional. The Data are saved in a table (row * column) known as a matrix.

We must use comma within the square brackets to build multidimensional array.

Example:


    int[,] arr=new int[3,3]; //declaration of 2D array  
    int[,,] arr=new int[3,3,3]; //declaration of 3D array 
 

 

 

C# Multidimensional Array Example

Let's see an instance of a multidimensional C# array that declares the two dimensional array, initializes them and passes through it.

Example:


public class Program
{
    public static void Main()
    {
        int[,] arr = new int[3, 3];//declaration of 2D array  
        arr[0, 1] = 10;//initialization  
        arr[1, 2] = 20;
        arr[2, 0] = 30;
        //traversal  
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                Console.Write(arr[i, j] + " ");
            }
            Console.WriteLine();//new line at each row  
        }
    }
}

Output:

0 10 0 
0 0 20
30 0 0

 

There are three ways in which C # is initialized during declaration.


    int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; 

The array size can be omitted.


    int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };  

The new operator can be omitted too.


    int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };  

 

 

Now, See a simple multidimensional array example that initializes array at the time of declaration.


   using System;

public class Program
{
    public static void Main()
    {
        int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//declaration and initialization  

        //traversal  
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                Console.Write(arr[i, j] + " ");
            }
            Console.WriteLine();//new line at each row  
        }
    }
}

Output:

1 2 3 
4 5 6
7 8 9