Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Multidimensional Arrays in C#

Introduction to Multidimensional Arrays

In C#, arrays can have multiple dimensions. These are known as multidimensional arrays. Multidimensional arrays are arrays of arrays, and they can be used to store data in a table-like structure or more complex structures.

Declaring Multidimensional Arrays

To declare a multidimensional array, you specify the number of dimensions and the size of each dimension. Here is the syntax for declaring a two-dimensional array:

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

This line declares a 2D array with 3 rows and 4 columns.

Initializing Multidimensional Arrays

Multidimensional arrays can be initialized at the time of declaration. Here is an example:

int[,] array = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };

This initializes a 2D array with 3 rows and 4 columns, filled with the provided values.

Accessing Elements in Multidimensional Arrays

Elements in a multidimensional array are accessed using indices. The first index specifies the row, and the second index specifies the column:

int value = array[1, 2]; // Accesses the element at row 1, column 2

In this example, value will be 7, since it's the element at row 1, column 2 in the initialized array.

Iterating Over Multidimensional Arrays

To iterate over the elements of a multidimensional array, you can use nested loops:

for(int i = 0; i < array.GetLength(0); i++) { for(int j = 0; j < array.GetLength(1); j++) { Console.Write(array[i, j] + " "); } Console.WriteLine(); }
1 2 3 4
5 6 7 8
9 10 11 12

This code will print out each element of the array in a matrix form.

Three-Dimensional Arrays

Three-dimensional arrays work similarly to two-dimensional arrays but with an additional dimension. Here is how you declare and initialize a 3D array:

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

To initialize and access elements in a 3D array, you use three indices:

int[,,] array3D = { { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }, { {13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24} } }; int value = array3D[1, 2, 3]; // Accesses the element at depth 1, row 2, column 3

In this example, value will be 24.

Conclusion

Multidimensional arrays provide a powerful way to store and manipulate data in C#. They can represent more complex data structures and are useful in many applications, such as mathematical computations, simulations, and data analysis. Understanding how to declare, initialize, and access these arrays is fundamental to utilizing their full potential in your programs.