Multi-dimensional Arrays
Learn to use multi-dimensional arrays in C#.
What is a multi-dimensional array?
In C#, a multi-dimensional array is an array that contains other arrays as its values or members. The container array is termed an outer array, and the member array is termed an inner array. An array is said to be a multi-dimensional array if it has another array as its members.
Can you think of some instances where we might have been using a structure that is the same as a multi-dimensional array? One such example is a crossword puzzle!
Individual values in multi-dimensional arrays
The individual values in a multi-dimensional array are accessed through multiple index numbers. The following is an example of a two-dimensional array in the following format:
array1[row number, column number];
Let’s take the example of the following array:
int[ , ] array1 = {{10, 20, 30},
{16, 18, 20}};
array1
is a two-dimensional array.- The value,
20
, can be accessed asarray1 [1, 2]
. - The number of indexes depends on the level of dimensions.
The general concepts of two-dimensional arrays, or n-dimensional arrays are implemented in C# as follows. The following program illustrates the structure of a two-dimensional array:
class Test{static void Main(){int[ , ] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; //declaring a 2-dimensional arrayfor (int i = 0; i < 3; i++) // printing a 2-dimensional array{for (int j = 0; j < 3; j++){System.Console.Write(array[i, j] + " ");}System.Console.WriteLine(" ");}}}
The following illustration shows the structure of the array above:
Here’s another example of the structure of a two-dimensional array:
class Test{static void Main(){int[ , ] array = {{1, 2}, {4, 5}, {7, 8}}; //declaring a 2-dimensional arrayfor (int i = 0; i < 3; i++) // printing a 2-dimensional array{for (int j = 0; j < 2; j++){System.Console.Write(array[i, j] + " ");}System.Console.WriteLine(" ");}}}
The following illustration shows the structure of the array above:
Here’s another example of a multi-dimensional array:
class Test{static void Main(){char[ , ] array = {{'A','B'}, {'C','D'}, {'E','F'}};for (int i = 0; i < 3; i++){for (int j = 0; j < 2; j++){System.Console.Write(array[i, j] + " ");}System.Console.WriteLine(" ");}}}
The following illustration shows the structure of the above array.
A mathematical matrix is implemented as a multi-dimensional array in C#, as shown in the following example:
...