Multidimensional array are arrays that use more than one index to access its content. Imagine a table with rows and columns, a multidimensional array can represent its data in a way a table can. Adding more indices increases the dimension of an array and makes it even more complex although it is very rare to use a multidimensional array that uses indexes more than two. The syntax of a multidimensional array that has two dimensions is as follows.

datatype[,] arrayName = new datatype[lengthX, lengthY];

And a multidimensional array with three dimensions has the following syntax.

datatype[, ,] arrayName = new datatype[lengthX, lengthY, lengthZ];

You can create an array with as much dimension as you can where each  dimension is specified by a length. Because using 3-dimensional arrays or arrays  with dimensions more than 2 are rare, let’s concentrate this lesson on using 2-dimensional arrays. The syntax requires the  datatype which is the type that the elements of that array possess. Next to the type is a pair of square brackets and a comma inside it. Note the number of commas to place inside the brackets. If we have a 2 dimension array, we place 1 comma and if we have a 3 dimension array, we put 2 commas so to find out how many commas to put, just remember (numberOfDimensions – 1). Next, we write the name of the variable and then we assign the dimension lengths by writing the new keyword, the datatype, and the lengths. In a 2-dimensional array, we need to give two length values, one for the x value and one for the y value where x represents the row of a table and y represents the column of a table if we look at it as a table. A 3-dimensional array can be represented by a cube like the word “3-D” suggest so the x would be the height, y would be the width, and z would be the depth. Let’s look at an example of a  2-dimensional array.

int[,] numbers = new int[3, 6];

The code above tells the compiler to allocate enough space for (3 * 6) array elements. The picture below shows where each array elements will be mapped if we think of them as cells in a table.

We pass 3 for the lengthX that’s why we have 3 rows and we gave 5 for  lengthY that’s why we have 5 columns. How do we initialize values in a multidimensional array? There are multiple ways of initializing values in a multidimensional array.

datatype[,] arrayName = new datatype[x, y] { { r0c0, r0c1, ... r0cX },
                                             { r1c0, r1c1, ... r1cX },
                                                       .
                                                       .
                                                       .
                                             { rYc0, rYc1, ... rYcX } };

To make it even simpler, you can ignore writing the new dataype[,] part.

datatype[,] arrayName = { { r0c0, r0c1, ... r0cX },
                          { r1c0, r1c1, ... r1cX },
                                   .
                                   .
                                   .
                          { rYc0, rYc1, ... rYcX } };

Here’s an example:

int[,] numbers = { { 1, 2, 3, 4, 5 },
                   { 6, 7, 8, 9, 10 },
                   { 11, 12, 13, 14, 15 } };

Or do everything manually and assign values to each element one by one like this:

array[0, 0] = value;
array[0, 1] = value;
array[0, 2] = value;
array[1, 0] = value;
array[1, 1] = value;
array[1, 2] = value;
array[2, 0] = value;
array[2, 1] = value;
array[2, 2] = value;

As you can see, accessing a 2-dimensional array’s element is as simple as indicating the x index and y index of the element inside a pair of brackets separated by a comma.

Iterating through a Multidimensional Array

Iterating through a multidimensional array can be a bit tricky. The easiest way perhaps is to use a foreach loop. You can also use a nested for loop. Let’s take a look at using foreach loop first.

using System;

namespace MultidimensionalArraysDemo
{
    public class Program
    {
        public static void Main()
        {
            int[,] numbers = { { 1, 2, 3, 4, 5 },
                               { 6, 7, 8, 9, 10 },
                               { 11, 12, 13, 14, 15 }
                             };

            foreach (int number in numbers)
            {
                Console.Write(number + " ");
            }
        }
    }
}

You can see how simple is it to cycle through the values of each element of a multidimensional array by just using a foreach  loop. By using a for each loop, we won’t be able to detect the end of a row in  case we want to bring the next row to the next line. You can easily do that with  the for each loop. The following program shows you how to use the for loop to read all the values in an array.

using System;

namespace MultidimensionalArraysDemo2
{
    public class Program
    {
        public static void Main()
        {
            int[,] numbers = { { 1, 2, 3, 4, 5 },
                               { 6, 7, 8, 9, 10 },
                               { 11, 12, 13, 14, 15 }
                             };

            for (int row = 0; row < numbers.GetLength(0); row++)
            {
                for (int col = 0; col < numbers.GetLength(1); col++)
                {
                    Console.Write(numbers[row, col] + " ");
                }

                //Go to the next line
                Console.WriteLine();
            }
        }
    }
}

Example 2 – Using a foreach Loop on a Multidimensional  Array

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

We can’t just use a plain for loop when accessing a multidimensional array. We need to use a nested for loop. On the first for loop  (line 14), we declared a variable which will loop through all the “rows” of our multidimensional array. It will loop until the value of row is less than the length of the first dimension. We used the method GetLength() of the Array class. This method gets the length of the array in a specified dimension. It has one parameter and that’s the dimension of the array. For example, to get the length of the first dimension of the array, we pass 0 as the value because it counts the dimension of an array from 0 to numberOfDimensions – 1.

Inside the first for loop is yet another for loop  (line 16). We declared another counter that will loop through all the “columns” of the current row in the loop cycle of the first loop. The condition involves using the method GetLength() again but this time, we pass 1 instead to get the length of the second dimension of the array. So for example, the current value of row is 0, then the second for loop will loop from [0, 0] up to [0, 4]. We then show a value of the current element in the loop, if the value of row is 0 and the value of col is 0, then it will show the value of numbers[0, 0].  After the second loop has finished doing the loop, it will execute the command  immediately after it, in this case, the next line informs the program to go to  the new line. The first loop will then repeat all of this process with the value of row increment incremented by 1. We will then repeat the second  for loop and display the values of the second row. The process will repeat until the row is less than the length of the first dimension.

Let’s apply what we have learn to make a program that get four grades of each of the three students. The program will determine the average grade for each student.

using System;

namespace MultidimensionalArrays3
{
    public class Program
    {
        public static void Main()
        {
            double[,] studentGrades = new double[3, 4];
            double total;

            for (int student = 0; student < studentGrades.GetLength(0); student++)
            {
                total = 0;

                Console.WriteLine("Enter grades for Student {0}", student + 1);

                for (int grade = 0; grade < studentGrades.GetLength(1); grade++)
                {
                    Console.Write("Enter Grade #{0}: ", grade + 1);
                    studentGrades[student, grade] = Convert.ToDouble(Console.ReadLine());
                    total += studentGrades[student, grade];
                }

                Console.WriteLine("Average is {0:F2}",
                                  (total / studentGrades.GetLength(1)));
                Console.WriteLine();
            }

        }
    }
}

Example 3 – Multidimensional Array Application

Enter grades for Student 1
Enter Grade #1: 92
Enter Grade #2: 87
Enter Grade #3: 89
Enter Grade #4: 95
Average is 90.75

Enter grades for Student 2
Enter Grade #1: 85
Enter Grade #2: 85
Enter Grade #3: 86
Enter Grade #4: 87
Average is 85.75

Enter grades for Student 3
Enter Grade #1: 90
Enter Grade #2: 90
Enter Grade #3: 90
Enter Grade #4: 90
Average is 90.00

The program declares a multidimensional array of type double  (line 9) because we are storing grades. We also declare a variable total  (line 10) that will be used soon for calculating the average of each student. We now enter the nested for loop  (line 12). On the first forloop, we declare a student variable that will determine which of the student the program will ask the grades for. We use GetLength() to determine the number of students. We enter the for loop body. Line 14 assigns a value of 0 to the variable total. We will know later why we did this. The program displays a prompt telling you to enter the grade of student number (student + 1). We add 1 to the student so that instead of displaying Student 0, it starts with 1 which is more natural.

We then arrive at the second for loop (line 18). We declare a counter variable grade and get the length of the second dimension of the array by calling GetLength(1). This length determines the number of grades the program will ask. The program will get each of the four grades for the current student. Each time the program gets the grade from the user, the grade obtained will be added to the totalvariable. When all the grades have been entered, the total variable already contains the sum of those grades.  Lines 25-26 will now display the average grade of the current student. Take note of the {0:F2}. This formats the grade into a fixed number with 2 decimal places. The average is then calculated by dividing the sum by the number of grades. We used GetLength(1) again to get the number of grades. The average grade is then displayed.