C# Jagged Array

In C#, a Jagged array is an array of arrays where each array can be of different sizes. It is also known as an "array of arrays". Unlike a multidimensional array, jagged arrays are dynamic in nature, i.e., the size of the array can be increased or decreased during runtime.

The syntax of declaring a Jagged array is:

1dataType[][] arrayName = new dataType[][] { 2 new dataType[] { element1, element2, ..., elementM }, 3 new dataType[] { element1, element2, ..., elementN }, 4 new dataType[] { element1, element2, ..., elementO }, 5 ... 6};

Here, dataType is the type of the elements of the array, arrayName is the name of the jagged array, and element1, element2, ... elementM are the elements of the array. The number of elements in each array can be different. In fact, the number of arrays itself can be different.

Let's look at an example of a jagged array:

1int[][] jaggedArray = new int[3][]; 2jaggedArray[0] = new int[] { 1, 2, 3 }; 3jaggedArray[1] = new int[] { 4, 5 }; 4jaggedArray[2] = new int[] { 6, 7, 8, 9 };

In the above example, we have declared a jagged array of size 3. The first array has 3 elements, the second array has 2 elements, and the third array has 4 elements.

We can access the elements of the jagged array using the following syntax:

1jaggedArray[i][j]

Here, i is the index of the array and j is the index of the element in the array.

We can also use loops to traverse the elements of the jagged array.

1for (int i = 0; i < jaggedArray.Length; i++) { 2 for (int j = 0; j < jaggedArray[i].Length; j++) { 3 Console.Write(jaggedArray[i][j] + " "); 4 } 5 Console.WriteLine(); 6}

In the above example, we have used two for loops to traverse the jagged array.