Home > C# > C# Multidimensional Arrays

A simple array stores values in sequential order and these values are in one row. i.e. if we see them on paper they will look like

int [] my_arr = new int [5] {1, 2, 3, 4, 5};

12345

C# Multidimensional Array

A C# multidimensional array is the one having more than one dimensions.i.e. it has rows and columns as well.

The simplest form of multidimensional arrays is a 2d array.  Memory actually stores each value in a row but on paper, we can say that they look like:

Row 1Column 1 Column 2Column 3Column 4
Row 2       //       //        //        // 
Row 3       //        //        //        // 
Row 4       //        //        //        // 

How to Declare a C# multidimensional array?

Data-type [,] array name; // each comma defines a new dimension.
E.g.
int [ , ] my_arr; // this is a 2d array declaration.
double [ , , ] my_arr; // this is a 3d array declaration.

Initializing the C# multidimensional arrays

We can initialize a multidimensional array in C# in the same way as we initialize an array. Its syntax is

int [ , ] my_arr = new int [array-rows, array columns];
E.g.
int [ , ] my_arr =  new int [2,4];// Here we have declared a 2d array with 2 rows and 4 columns.
Similarly, other multidimensional arrays can be initialized as well.
E.g.
double [, , ,] my_array = new double [1,2,3,4];

Below example will explain the working of multidimensional arrays.

Example Program

using System;
namepace multidimensional_arrays
{
     class Program
     {
          static void Main(string[] args)
          {
               int[,,] my_arr= new int[2, 3, 2];
               my_arr[0, 0, 0] = 7;
               my_arr[0, 1, 0] = 70;
               my_arr[0, 2, 0] = 700;
               my_arr[1, 0, 1] = 7000;
               my_arr[1, 1, 1] = 70000;
               my_arr[1, 2, 1] = 700000;
               Console.WriteLine("Value at my_arr[0,0,0] = " + my_arr[0, 0, 0]);
               Console.WriteLine("Value at my_arr[0,1,0] = " + my_arr[0, 1, 0]);
               Console.WriteLine("Value at my_arr[0,2,0] = " + my_arr[0, 2, 0]);
               Console.WriteLine("Value at my_arr[1,0,1] = " + my_arr[1, 0, 1]);
               Console.WriteLine("Value at my_arr[1,1,1] = " + my_arr[1, 1, 1]);
               Console.WriteLine("Value at my_arr[1,2,1] = " + my_arr[1, 2, 1]);
          }
     }
}

Output
c# multidimensional array

From the example above we know now that how we can access elements of a multidimensional array. Though we didn’t access all elements of the above-initialized array.

Looping through multidimensional Arrays

We can access elements can of a multidimensional array using loops. Here are a few examples.
For loop

using System;
namespace multidimensional_arrays
{
     class Program
     {
          static void Main(string[] args)
          {
               int[,] my_arr = new int[2,4];
               for (int i=0;i<2;i++)
               {
                    for(int j=0;j < 4;j++)
                    {
                         Console.WriteLine("Plese Enter A Value : ");
                         my_arr[i, j] = Convert.ToInt32(Console.ReadLine());
                    }
               }
               for (int i = 0; i < 2; i++)
               {
                    for (int j = 0; j < 4; j++)
                    {
                         Console.WriteLine("Array elements are : " + my_arr[i,j]);
                    }
               }
          }
     }
}

Output
loop through C# multidimensional array
Similarly, we can use other loops as well with multidimensional arrays.

Jagged array in C#

Another form of multidimensional arrays is the jagged array which is an array of arrays.
In jagged we combine a number of arrays and represent them as a single array. Each index of the jagged array is actually representing another array.
In C# we declare a jagged array as:

Data-type [] [] array-name;
E.g.
double [] [] my_arr;

Initializing jagged array
You can initialize a jagged array in C# as:

Data-type [] [] array-name = new data-type [size] [];
E.g.
double [] [] my_arr = new double [3] [];

Here is a simple example program explaining the working of jagged arrays.

using System;
namespace multidimensional_arrays
{
     class Program
     {
          static void Main(string[] args)
          {
               int[][] my_arr = new int [3][]; // Declaring a jagged array in C#.
               // storing arrays at each index.
               my_arr[0] = new int[] {10, 20, 30};
               my_arr[1] = new int[] {40, 50, 60 };
               my_arr[2] = new int[] {70, 80, 90 };
               for (int i = 0; i < 3; i++)
               {
                    for (int j = 0; j < 3; j++)
                    {
                         Console.WriteLine("Value stored at my_arr[{0}][{1}] = 
                         {2}", i, j, my_arr[i][j]);
                    }
               }
          }
     }
}

Output
Jagged Array in C#
Here we created a jagged array named my_arr in which we stored three arrays of the same data type at each of its indexes. Practically Jagged array in c# does not store arrays at the index yet, that index points to a memory location of another array.

Arrays To functions

You can pass arrays to functions as well as their arguments. Here are a few examples showing how you can pass arrays to methods in C#. Generally, an array can be passed to a function and with it, the array size is also passed to the function to perform particular tasks with the array. Below example shows how to pass an array to a function along with its size and then function performs its task with the array.
Example Program.

using System;
namespace arrays_to_function
{
    class Program
    {
        public double Calculate_Average(int[] my_arr, int array_size)
        {
            int sum = 0,i;
            for(i=0; i < array_size; ++i)
            {
                sum += my_arr[i];
            }
            double average = sum / i;
            return average;
        }
        static void Main(string[] args)
        {
            int array_size = 5;
            int[] my_arr = new int[array_size];
            for(int i=0;i < array_size;i++)
            {
                Console.WriteLine("Please enter an integer value : ");
                my_arr[i] = Convert.ToInt32(Console.ReadLine());
            }
            Program p = new Program();
            Console.WriteLine("Average of values of array = "+
            p.Calculate_Average(my_arr,array_size));
        }
    }
}

Output
C# arrays to function

C# Param Arrays

Sometimes we are not sure about what number of arguments our function receives or what number of arguments a user can pass to a function. So we need to define our function in such a way that it can accept any number of arguments. C# provides a mechanism for this purpose. We use C# params arrays for this purpose. Below example demonstrates this in detail.

Example program

using System;
namespace arrays_to_function
{
    class Program
    {
        public double Calculate_Average(params int[] my_arr)
        {
            int sum = 0,j= 0;
            foreach (int i in my_arr)
            {
                sum += i;
                j++;
            }
            double average = sum / j;
            return average;
        }
        static void Main(string[] args)
        {
            int no1, no2, no3, no4, no5; 
            Console.WriteLine("Please enter an integer value : ");
            no1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please enter an integer value : ");
            no2 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please enter an integer value : ");
            no3 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please enter an integer value : ");
            no4 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please enter an integer value : ");
            no5 = Convert.ToInt32(Console.ReadLine());

            Program p = new Program();
            Console.WriteLine("Average of  5 values = " +p.Calculate_Average(no1,no2,no3,no4,no5));
            Console.WriteLine("Average of  3 values = " +p.Calculate_Average(no1, no2, no3));
        }
    }
}

Output

C# param arrays

In the above example, we passed the different number of arguments to the same function. And in both cases, it worked fine. This is how params array helps when we don’t know the exact number of arguments passed to a function.

Different built-in functions are also available in C# to work with arrays.

They include:

Clear
Copy(Array, Array, Int32)
CopyTo(Array, Int32)
GetLength
GetLongLength and more.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.