Latest web development tutorials

C # multidimensional arrays

C # arrays C # arrays

C # supports multidimensional arrays. Multidimensional arrays, also known as a rectangular array.

You can declare a two-dimensional array of string variables, as follows:

string [,] names;

Alternatively, you can declare a three-dimensional array of int variables, as follows:

int [,,] m;

Two-dimensional array

The simplest form of a multidimensional array is a two-dimensional array. A two-dimensional array, in essence, is a list of one-dimensional array.

A two-dimensional array can be considered a form x row and y column with. Here is a two-dimensional array containing 3 rows and 4:

Two-dimensional array in C #

Thus, each element of the array is the use of the form a [i, j] element names to identify where a name is an array, i, and j is the unique identifier in a subscript of each element.

Two-dimensional array initialization

Multidimensional arrays can be initialized in parentheses to the specified value for each row. Here is an array of four rows with 3.

int [,] a = int [3,4] = {  
 {0, 1, 2, 3} / * initialize the index number of rows 0 * /
 {4, 5, 6, 7} / * initialize an index number of row 1 * /
 {8, 9, 10, 11} / * initialize the index number for the row 2 * /
};

Two-dimensional array element access

Two-dimensional array element by using the subscript (ie, the array row index and column index) to visit. E.g:

int val = a [2,3];

The above statement will get the first four elements in the array on line 3. You can be verified by the above diagram. Let's look at the following program, we will use a nested loop to process two-dimensional array:

using System;

namespace ArrayApplication
{
    class MyArray
    {
        static void Main (string [] args)
        {
            / * With a 5 row two arrays * /
            int [,] a = new int [5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8}};

            int i, j;

            / * Output value 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

C # arrays C # arrays