• Home
  • Multi Dimensional Array

Multi Dimensional Array

Agenda

Multi-Dimensional Array in C#

 
int[,] array2d; // two-dimensional array

 
int[, ,] array3d; // three-dimensional array

 
int[, , ,] array4d ; // four-dimensional array

Multi-Dimensional Array in C# - Contd.

Multi-Dimensional Array in C# - Contd.

int[,] arr3R3C = new int[3, 3];//declaration of 2D array

arr3R3C[0, 1] = 10;//initialization

arr3R3C[1, 2] = 20;

arr3R3C[2, 0] = 30;

arr3R3C[2, 1] = 40;

arr3R3C[2, 2] = 50;

//traversal

for (int i = 0; i < 3; i++)

{

for (int j = 0; j < 3; j++)

{

Console.Write(arr3R3C[i, j] + ” “); //undefined elements will take the
default value of data type, for int default value will be 0

}

Console.WriteLine();//new line at each row

}


  int[,] intArray = { { 1, 2, 3 }, { 4, 5, 6 } };

intArray[0, 1] = 12;
Console.WriteLine(intArray[0,1]);

foreach (int i in intArray)
{
Console.WriteLine(i);
}

int[,] arr3R3C = new int[3, 3];//declaration of 2D array

arr3R3C[0, 1] = 10;//initialization
arr3R3C[1, 2] = 20;
arr3R3C[2, 0] = 30;
arr3R3C[2, 1] = 40;
arr3R3C[2, 2] = 50;

//traversal
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(arr3R3C[i, j] + " "); //undefined elements will take the default value of data type, for int it will be 0
}

Console.WriteLine();//new line at each row
}

string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" }, { "five", "six" } };
foreach (string s in array2Db)
{
System.Console.Write("{0} ", s);
}

var allArrayLength = intArray.Length;
var total = 1;
for (int i = 0; i < intArray.Rank; i++)
{
total *= intArray.GetLength(i);
}

System.Console.WriteLine("{0} equals {1}", allArrayLength, total);

for (int i = 0; i < intArray.GetLength(0); i++)
{
Console.Write("Row " + i + ": ");

for (int j = 0; j < intArray.GetLength(1); j++)
{
Console.Write(intArray[i, j] + " ");

}
Console.WriteLine();

}
int[,] array2D = new int[,] { { 10, 2 }, { 3, 4 }, { 5, 7 } };

foreach (int i in array2D)
{
System.Console.Write("{0} ", i);
}