Multi Dimensional Array In C#

The multi dimensional array in C# is like type of array that store more than one row to store data on it. The multi dimensional array is also known as rectangular array in c sharp because it has same length of each row. It can be two dimensional array or three dimensional array or more. It contains more than one coma (,) within single rectangular brackets (“[ , , ,]”). To storing and retrieve the elements from multidimensional array, you required to use nested loop in program. The below example will help you to figure out the concept of multidimensional array.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Multi_Dimensional_Array_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j;
            //Declaring multi dimensional array
            string[,] Books = new string[3, 3];
            for (i = 0; i < 3; i++)
            {
                for (j = 0; j < 3; j++)
                {
                    Console.Write("\nEnter Book Name for {0}. Row and {1}. column:\t", i + 1, j + 1);
                    Books[i, j] = Console.ReadLine();
                }
            }
            Console.WriteLine("\n\n=========================");
            Console.WriteLine("All the element of Books array is:\n\n");
            //Formatting Output
            Console.Write("\t1\t2\t3\n\n");
            //outer loop for accessing rows
            for (i = 0; i < 3; i++)
            {
                Console.Write("{0}.\t", i + 1);
                //inner or nested loop for accessing column of each row
                for (j = 0; j < 3; j++)
                {
                    Console.Write("{0}\t", Books[i, j]);
                }
                Console.Write("\n");
            }
            Console.WriteLine("\n\n=========================");
            Console.ReadLine();
        }
    }
}

In the above example, we create a two dimensional array named Books which size is [3,3].In multi dimensional array has three rows and each rows contains three columns. Each row can be retrieve using outer loop and each column of rows can be retrieve using nested loop inside the outer loop as follow.

for (i = 0; i < 3; i++) //outer loop for accessing rows
{
   Console.Write("{0}.\t", i + 1);
   //inner or nested loop for accessing column of each row
   for (j = 0; j < 3; j++)
    {
      Console.Write("{0}\t", Books[i,j]);
    }
   Console.Write("\n");
}

Leave a Reply

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