# Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

## C# Multidimensional Arrays

The multidimensional array is also known as rectangular arrays in C#. It can be two dimensional or three dimensional. The data is stored in tabular form (row * column) which is also known as matrix.

To create multidimensional array, we need to use comma inside the square brackets. For example:

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

C# Multidimensional Array Example

Let's see a simple example of multidimensional array in C# which declares, initializes and traverse two dimensional array.

1. using System;
2. public class MultiArrayExample
3. {
4.     public static void Main(string[] args)
5.     {
6.         int[,] arr=new int[3,3];//declaration of 2D array
7.         arr[0,1]=10;//initialization
8.         arr[1,2]=20;
9.         arr[2,0]=30;
10.
11.         //traversal
12.         for(int i=0;i<3;i++){
13.             for(int j=0;j<3;j++){
14.                 Console.Write(arr[i,j]+" ");
15.             }
16.             Console.WriteLine();//new line at each row
17.         }
18.     }
19. }

Output:

```0 10 0
0 0 20
30 0 0```

C# Multidimensional Array Example: Declaration and initialization at same time

There are 3 ways to initialize multidimensional array in C# while declaration.

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

We can omit the array size.

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

We can omit the new operator also.

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

Let's see a simple example of multidimensional array which initializes array at the time of declaration.

1. using System;
2. public class MultiArrayExample
3. {
4.     public static void Main(string[] args)
5.     {
6.         int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//declaration and initialization
7.
8.         //traversal
9.         for(int i=0;i<3;i++){
10.             for(int j=0;j<3;j++){
11.                 Console.Write(arr[i,j]+" ");
12.             }
13.             Console.WriteLine();//new line at each row
14.         }
15.     }
16. }

Output:

```1 2 3
4 5 6
7 8 9```