Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to access elements from multi-dimensional array in C#?
To access elements from a multi-dimensional array in C#, you specify indices for each dimension using square brackets with comma-separated values. For example, a[2,1] accesses the element at row 3, column 2 (using zero-based indexing).
Syntax
Following is the syntax for accessing elements from a multi-dimensional array −
arrayName[index1, index2, ...indexN]
For a 2D array, you use two indices −
int element = array[rowIndex, columnIndex];
Understanding Array Indexing
Multi-dimensional arrays use zero-based indexing, meaning the first element is at index [0,0]. Consider this 4×2 array structure −
Example
The following example demonstrates how to access elements from a 2D array −
using System;
namespace Program {
class Demo {
static void Main(string[] args) {
int[,] a = new int[4, 2] {{0,0}, {1,2}, {2,4}, {3,6} };
int i, j;
Console.WriteLine("All elements in the array:");
for (i = 0; i < 4; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
Console.WriteLine("\nAccessing specific elements:");
Console.WriteLine("Element at [2,1]: " + a[2,1]);
Console.WriteLine("Element at [0,0]: " + a[0,0]);
Console.WriteLine("Element at [3,1]: " + a[3,1]);
}
}
}
The output of the above code is −
All elements in the array: a[0,0] = 0 a[0,1] = 0 a[1,0] = 1 a[1,1] = 2 a[2,0] = 2 a[2,1] = 4 a[3,0] = 3 a[3,1] = 6 Accessing specific elements: Element at [2,1]: 4 Element at [0,0]: 0 Element at [3,1]: 6
Accessing 3D Array Elements
For arrays with more dimensions, you simply add more indices −
using System;
class Program {
static void Main() {
int[,,] cube = new int[2, 2, 2] {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
Console.WriteLine("3D Array Elements:");
Console.WriteLine("cube[0,0,0] = " + cube[0,0,0]);
Console.WriteLine("cube[0,1,1] = " + cube[0,1,1]);
Console.WriteLine("cube[1,0,1] = " + cube[1,0,1]);
Console.WriteLine("cube[1,1,0] = " + cube[1,1,0]);
}
}
The output of the above code is −
3D Array Elements: cube[0,0,0] = 1 cube[0,1,1] = 4 cube[1,0,1] = 6 cube[1,1,0] = 7
Conclusion
Accessing multi-dimensional array elements in C# requires specifying indices for each dimension using comma-separated values within square brackets. Remember that arrays use zero-based indexing, so the first element is at [0,0] for 2D arrays or [0,0,0] for 3D arrays.
