Curriculum
In C#, a jagged array is an array of arrays where each subarray can have a different length. Jagged arrays are useful for storing and manipulating data that has a variable number of elements in each dimension. Jagged arrays are also known as arrays of arrays.
Here is an example of declaring and initializing a jagged array in C#:
int[][] jaggedArray = new int[3][]; jaggedArray[0] = new int[] { 1, 2, 3 }; jaggedArray[1] = new int[] { 4, 5 }; jaggedArray[2] = new int[] { 6, 7, 8, 9 };
This creates a jagged array called jaggedArray
with three elements, where each element is an integer array of varying length. The first element has three values, the second element has two values, and the third element has four values.
You can access the elements of a jagged array using nested square brackets, just like with multi-dimensional arrays. Here is an example of accessing an element in the jaggedArray
:
int element = jaggedArray[1][0]; // this retrieves the value 4
This retrieves the value in the second element and first index of the jaggedArray
, which is 4.
Jagged arrays can be useful in a variety of situations, such as when you need to store data that has a variable number of elements or when you need to create dynamic data structures that can be resized at runtime.