DEV Community

CodetoLive blog
CodetoLive blog

Posted on • Originally published at codetolive.in on

Multidimensional array in C#

INDEX

  • What is an array?
  • What is a multidimensional array?
  • 2d and 3d arrays
  • Examples

1. What is an Array?

Arrays are used to store multiple values in a single variable instead of in separate variables. It can be single dimensional, multidimensional, or jagged.

2. What is a multidimensional array?

It is an array of arrays and has more than one dimension. The most common is a two-dimensional array, i.e., 2D.

3. What is 2D?

A 2D array is a matrix that consists of rows and columns.

3.1 2D array with an int data type without specifying the index

int[,] arrayNumbers = new int[,] { {1, 2}, {3, 4} };

Enter fullscreen mode Exit fullscreen mode
Col 0 Col 1
Row 0 1 2
Row 1 3 4

3.1.1 Output:

Console.WriteLine(arrayNumbers[0][1]);

Console.WriteLine(arrayNumbers[1][0]);

2

3

3.2 2D array with int data type and specified index

int[,] arrayNumbers = new int[3,2] { {1, 2}, {3, 4}, {5,6} };

Enter fullscreen mode Exit fullscreen mode
Col 0 Col 1
Row 0 1 2
Row 1 3 4
Row 2 5 6

3.2.1 Output:

Console.WriteLine(arrayNumbers[0][1]);

Console.WriteLine(arrayNumbers[1][0]);

2

3

3.3 2D array with string data type

string[,] arrayCities = new string[2,2] { {”Chennai”, “Bangalore”}, {”Delhi”, “Pune”} };

Enter fullscreen mode Exit fullscreen mode
Col 0 Col 1
Row 0 Chennai Bangalore
Row 1 Delhi Pune

3.3.1 Output:

Console.WriteLine(arrayNumbers[0][1]);

Console.WriteLine(arrayNumbers[1][0]);

Bangalore

Delhi

4. What is 3D?

3D arrays are used to hold multiple 2D arrays, and they supports up to 32 dimensions. It can be declared by adding commas in the square brackets. For example, [,] - two-dimensional array

[, ,] - three-dimensional array

[, , ,] - four-dimensional array, and so on.

1st index: indicates the number of layers

2nd index: number of rows

3rd index: number of cols

4.1 Examples

4.1.1 Single-layer

int[, ,] array3d1 = new int[1, 2, 2]{
                { { 1, 2}, { 3, 4} }
            };

Enter fullscreen mode Exit fullscreen mode

4.1.2 Two layers with 2 rows and 2 columns

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

Enter fullscreen mode Exit fullscreen mode

4.1.3 Two layers with 2 rows and 3 columns


int[, ,] array3d3 = new int[2, 2, 3]{
                { { 1, 2, 3}, {4, 5, 6} },
                { { 7, 8, 9}, {10, 11, 12} }
            };

Enter fullscreen mode Exit fullscreen mode

4.1.4 Output:

Console.WriteLine(array3d1[0, 0, 0]); // Output = 1

Console.WriteLine(array3d1[0, 0, 1]); // Output = 2

Console.WriteLine(array3d2[0, 1, 0]); // Output = 3

Console.WriteLine(array3d2[1, 1, 1]); // Output = 7

Console.WriteLine(array3d3[0, 1, 2]); // Output = 6

Console.WriteLine(array3d4[1, 0, 2]); // Output = 9

Top comments (0)