Single Dimensional, Multi-Dimensional & Jagged Arrays in C#
Single Dimensional Arrays
A single-dimensional array is the simplest form of an array in C#. It stores a collection of elements of the same type, where each element is accessed using an index. The index starts from 0.
Example of Single Dimensional Array:
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
In this example, a single-dimensional array numbers
is created and its elements are printed using a loop.
Multi-Dimensional Arrays
Multi-dimensional arrays, also called rectangular arrays, are arrays where elements are arranged in rows and columns (like a matrix). You access elements by specifying multiple indices.
Example of Multi-Dimensional Array:
int[,] matrix = new int[3, 3]
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
In this example, a two-dimensional array matrix
is created and its elements are printed row by row.
Jagged Arrays
A jagged array is an array of arrays, meaning each element of the array is another array. Jagged arrays allow each inner array to have a different size.
Example of Jagged Array:
int[][] jaggedArray = new int[3][]
{
new int[] {1, 2},
new int[] {3, 4, 5},
new int[] {6, 7, 8, 9}
};
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
In this example, a jagged array is created, where each inner array has a different length. The elements are printed using a nested loop.
Key Points to Remember
- Single-dimensional arrays store elements in a linear order, accessed by a single index.
- Multi-dimensional arrays store elements in a matrix form (rows and columns), accessed by multiple indices.
- Jagged arrays are arrays of arrays, where each inner array can have a different size.