CS Jagged Arrays

In C #, the jagged array is also called the array of the arrays, because the arrays are its elements. Jagged array element size can be differ.

Jagged Array Declaration

Declaring jagged array with two items.

``````
int[][] arr = new int[2][];

``````

Jagged Array Initialization

Initialization Jagged array. The size of the element can be vary.

``````
arr[0] = new int[4];
arr[1] = new int[6];

``````

Jagged Array initialization and fill with elements

Example for initializing and filling in jagged array elements

``````
arr[0] = new int[4] { 11, 21, 56, 78 };
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };

``````

``````
arr[0] = new int[] { 11, 21, 56, 78 };
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };

``````

C # jagged example that declares, initializes and traverse jagged arrays.

``````
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[2][];// Declare the array

arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };

// Traverse array elements
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
}
}

``````

Output:

``11 21 56 78 ``42 61 37 41 59 63``

See an example in which the jagged array is initialized during statement.

``````
int[][] arr = new int[3][]{
new int[] { 11, 21, 56, 78 },
new int[] { 2, 5, 6, 7, 98, 5 },
new int[] { 2, 5 }
};

``````

Example:

``````
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[3][]{
new int[] { 11, 21, 56, 78 },
new int[] { 2, 5, 6, 7, 98, 5 },
new int[] { 2, 5 }
};

// Traverse array elements
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
}
}

``````

Output:

``11 21 56 78 ``2 5 6 7 98 5 ``2 5``