Lesson 8.2

Multi-Dimensional Array in C# with programming Example


Objective

What is multi-dimensional array in c#?
How to declare two dimensional or multidimensional array?
Programming Example

What is multidimensional array in c#?

Multi-Dimensional array is such type of array which has more than one dimension or more than one row. It structure is like a cube or rectangular and its data can be accessed using nested loop. The outer loop iterates through the row and inner loop iterate through the column. Multi-dimensional array can store multiple values than one dimensional array.

How to declare multi-dimensional array?

Multi-Dimensional array can be declared same as one dimensional array only difference is it has coma (,) in declaration. For Example:

Two Dimensional Array

int[,] array = new int[4, 2];

It means this array has 4 rows with 2 columns


or,

Multi-Dimensional Array

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

It means this array has 4 floors of data and each floor contains 2 rows and 3 columns.

One Dimensional Array

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace multi_dimensional_array
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating String Array
            string[,] book = new string[4, 3];

            //Row 1
            book[0, 0] = "Book";
            book[0, 1] = "Author Name";
            book[0, 2] = "Age";

            //Row 2
            book[1,0] = "C#";
            book[1, 1] = "Lyric Angel";
            book[1, 2] = "30 Years Old";

            //Row 3
            book[2, 0] = "Java";
            book[2, 1] = "Eddy Angelil";
            book[2, 2] = "34 Years Old";

            //Row 4
            book[3, 0] = "PHP";
            book[3, 1] = "Raine Finley";
            book[3, 2] = "28 Years Old";

            //Printing Value
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("\n");
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(book[i, j]+"\t");
                }
            }
            Console.ReadKey();
        }
    }
}


Output

BookAuthor NameAge
C#Lyric Angel30 Years Old
JavaEddy Angelil34 Years Old
PHPRaine Finley28 Years Old
__

Summary

In this chapter you have learned about multi-dimensional array with programming example. The next chapter will explain Array Parameter.

BackNext