Multidimensional Arrays


A multidimensional array is an array with 2 or more dimensions. Multidimensional arrays are accessed using 2 or more indices.

Two Dimensional Arrays

To declare and allocate a 2 dimensional array of floating point values the following syntax is used.

double[,] ad2d = new double[3,4];

This declares this declares an 2 dimensional array that has 12 elements in the array in the form of 3 rows and 4 columns. Incorporating this declaration into a program produces the following example.

// Array 2D - 2 Dimensional Array Example

using System;

enum Limits
{
    Rows = 2,
    Cols = 3
}

class Program
{
    static void Main()
    {
        double[,] ad2 = new double[(int)Limits.Rows, (int)Limits.Cols];

        for (int i = 0; i < (int)Limits.Rows; i++)
            for (int j = 0; j < (int)Limits.Cols; j++)
                ad2[i, j] = .5 + i * (int)Limits.Cols + j;

        for (int i = 0; i < (int)Limits.Rows; i++)
        {
            for (int j = 0; j < (int)Limits.Cols; j++)
            {
                Console.Write(ad2[i, j]);
                if (j != (int)Limits.Cols-1) Console.Write(", ");
            }
            Console.WriteLine();
        }
    }
}

The printout from this program is shown below.

0.5, 1.5, 2.5
3.5, 4.5, 5.5

From the printout it is apparent that:

af[0, 0] = 0.5
af[0, 1] = 1.5
af[0, 2] = 2.5

af[1, 0] = 3.5
af[1, 1] = 4.5
af[1, 2] = 5.5

The two dimensional array is stored in row order with the row being the first index. This fact generalizes to arrays of higher dimensions.

Arrays of Three or More Dimensions

The general form of multidimensional array declaration is shown below:

type[,...,] name = new type[size1,size2,...,sizeN];

where the first elipsis indicates a variable number of commas. For example, to declare a three dimensional, 2x3x4 array the following suffices.

int[,,] ai = new int[2, 3, 4];

To give element 1,2,3 a value the following code may be used.

ai[1, 2, 3] = 100;

Initializing Multidimensional Arrays

Just as single dimensional arrays have a specific syntax for initializing fixed arrays, multidimensional arrays have a similar syntax. That syntax is shown below for a 2 dimensional array.

type[,] array-name = { {value, value, ..., value},
                       {value, value, ..., value},
                       ...
                       {value, value, ..., value} };

An example of this syntax is shown in the program below, which redoes a previous program.

// Array2DB - 2 Dimensional Array Example

using System;

class Program
{
    static void Main()
    {
        double[,] ad2 = { { 0.5, 1.5, 2.5 },
                          { 3.5, 4.5, 5.5 } };

        for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                Console.Write(ad2[i, j]);
                if (j != 2) Console.Write(", ");
            }
            Console.WriteLine();
        }
    }
}

The output is the same as the previous program.