An array is the collection of homogeneous elements which stored in a contiguous memory location by using the same variable name. Elements of an array are accessed by their index value. Array index start with 0 and go up-to-the length of an array elements(n) less than -1.i.e.(n-1).
An array can be Single dimensional or Multidimensional.
Here, we will discuss the Multidimensional array.
-
A multidimensional array is an array which contains more than one arrays to store data on it.
-
The length of each row in multidimensional is same, therefore, it is also known as a rectangular array. The multidimensional array contains a 2D array or 3D array or more.
-
Multidimensional arrays look like a table in which each element has a row and a column value.
For example:
Syntax for 2-dimensional array:
int [,] arrayname=new int[9,32];
Syntax for 3-dimensional array:
int [, ,] arrayname=new int[29,32,89];
Array Initialization:
For 2-dimensional array initialization:
We can initialize the 2-dimensional array in three way:
1. int[,] a = new int[ , ] { { 11, 20 }, { 3, 42 }, { 35, 60 }, { 43, 22 } };
2. int[,] a = new int[3, 2] { { 10, 32 }, { 31, 44 }, { 25, 64 } };
3. int[,] a= new int [3,2];
a[0,0]=1;
a[0,1]=2;
a[1,0]=4;
a[1,1]=5;
a[2,0]=7;
a[2,1]=8;
For 3-dimensional array initialization:
We can initialize the 3-dimensional array in three way:
int[, ,] b = new int[ , , ] { { { 19, 22, 32 }, { 40, 45, 26 } },
{ { 17, 38, 49 }, { 10, 76, 25 } } };
int[, ,] b = new int[2, 2, 3] { { { 19, 22, 32 }, { 40, 45, 26 } },
{ { 17, 38, 49 }, { 10, 76, 25 } } };
int[, ,] b = new int[3, 5, 4];
b[0, 0, 0] = 10;
b[0, 1, 0] = 12;
b[0, 2, 0] = 32;
b[0, 3, 0] = 24;
b[0, 4, 0] = 75;
b[1, 1, 1] = 20;
b[2, 2, 2] = 35;
b[2, 2, 3] = 14;
C# Code for accessing Two-Dimensional Array Elements
using System;
namespace Sample ArrayProgram
{
class SampleArray
{
static void Main(string[] args)
{
int[,] a = new int[2, 3] {{1,2,3}, {4,5,6}};
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
Console.WriteLine( a[i,j]);
}
}
Console.ReadKey();
}
}
}
C# Code for accessing Three-Dimensional Array Elements
namespace Sample ArrayProgram
{
class SampleArray
{
static void Main(string[] args)
{
int[, ,] b = new int[2, 2, 3] { { { 19, 22, 32 }, { 40, 45, 26 } }, { { 17, 38, 49 }, { 10, 76, 25 } } };
for (int i = 0; i < b.GetLength(2); i++)
{
for (int j = 0; j < b.GetLength(1); j++)
{
for (int k = 0; k < b.GetLength(0); k++)
{
Console.Write(b[k, j, i]);
}
}
Console.WriteLine();
}
}
}
}
Multidimensional array has some advantages:
1. The multidimensional array is stored in a contiguous memory location so that it is easy to access its elements.
2. The multidimensional array allows us to represent multiple data items of the same type by use of a single variable name.
3. Elements of a multidimensional array take less access time.
0 Comment(s)