C # multidimensional array
C # supports multidimensional arrays. A multidimensional array is also called a rectangular array.
You can declare a string
two-dimensional array of variables, as follows:
string [,] names;
Alternatively, you can declare a int
three-dimensional array of variables, as follows:
int [ , , ] m;
Two-dimensional array
The simplest form of a multidimensional array is a two-dimensional array. A two-dimensional array is essentially a list of one-dimensional arrays.
A two-dimensional array can be thought of as a table with x rows and y columns.
Therefore, each element in the array is in the form of a[ i , j ]
identified by the element name of the, where a
is the array name i
and j
are subscripts that uniquely identify each element in a
.
Initialize two-dimensional array
Multidimensional arrays can be initialized by specifying values for each rowin parentheses. The following is an array with three rows and four columns.
int [,] a = new int [3,4] {
{0, 1, 2, 3} , /* initialize rows with index number 0 */
{4, 5, 6, 7} , /* initialize rows with index number 1 */
{8, 9, 10, 11} /* initialize rows with index number 2 */
};
Access two-dimensional array elements
Elements in a two-dimensional array are accessed by using subscripts (that is, row and column indexes of the array). For example:
int val = a[2,3];
The above statement will get the fourth element in the third line of the array. You can verify it through the diagram above. Let’s take a look at thefollowing program, where we will use nested loops to deal with two-dimensional arrays:
Example
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
/* an array with 5 rows and 2 columns */
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8}
};
int i, j;
/* output the values of each element in the array */
for (i = 0; i < 5; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8