In this source code example, we will demonstrate how to create a three-dimensional array in C#.
C# Three Dimensional Array Example
The below C# program demonstrate how to create a three-dimensional array, access elements from a three-dimensional array and loop over a three-dimensional array:
using System;
public class ArrayDemo
{
public static void Main(string[] args)
{
int[,,] numbers =
{
{{1, 2, 3}},
{{4, 5, 6}},
{{7, 8, 9}},
{{10, 11, 12}}
};
// access first element from the first row
Console.WriteLine("Element at index [0, 0, 0] : "+numbers[0, 0, 0]);
// access first element from second row
Console.WriteLine("Element at index [1, 0, 0] : "+numbers[1, 0, 0]);
// access first element from third row
Console.WriteLine("Element at index [2, 0, 0] : "+numbers[2, 0, 0]);
// access first element from fourth row
Console.WriteLine("Element at index [3, 0, 0] : "+numbers[3, 0, 0]);
int d1 = numbers.GetLength(0);
int d2 = numbers.GetLength(1);
int d3 = numbers.GetLength(2);
for (int i=0; i<d1; i++)
{
for (int j=0; j<d2; j++)
{
for (int k=0; k<d3; k++)
{
Console.Write(numbers[i, j, k] + " ");
}
}
}
Console.Write('\n');
}
}
Output:
Element at index [0, 0, 0] : 1
Element at index [1, 0, 0] : 4
Element at index [2, 0, 0] : 7
Element at index [3, 0, 0] : 10
1 2 3 4 5 6 7 8 9 10 11 12
Comments
Post a Comment