# Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

## C# Jagged Arrays

In C#, jagged array is also known as "array of arrays" because its elements are arrays. The element size of jagged array can be different.

Declaration of Jagged array

Let's see an example to declare jagged array that has two elements.

int[][] arr = new int[];

Initialization of Jagged array

Let's see an example to initialize jagged array. The size of elements can be different.

1. arr = new int;
2. arr = new int;

Initialization and filling elements in Jagged array

Let's see an example to initialize and fill elements in jagged array.

1. arr = new int { 11, 21, 56, 78 };
2. arr = new int { 42, 61, 37, 41, 59, 63 };

Here, size of elements in jagged array is optional. So, you can write above code as given below:

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

C# Jagged Array Example

Let's see a simple example of jagged array in C# which declares, initializes and traverse jagged arrays.

1. public class JaggedArrayTest
2. {
3.     public static void Main()
4.     {
5.         int[][] arr = new int[];// Declare the array
6.
7.         arr = new int[] { 11, 21, 56, 78 };// Initialize the array
8.         arr = new int[] { 42, 61, 37, 41, 59, 63 };
9.
10.         // Traverse array elements
11.         for (int i = 0; i < arr.Length; i++)
12.         {
13.             for (int j = 0; j < arr[i].Length; j++)
14.             {
15.                 System.Console.Write(arr[i][j]+" ");
16.             }
17.             System.Console.WriteLine();
18.         }
19.     }
20. }

Output:

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

Initialization of Jagged array upon Declaration

Let's see an example to initialize the jagged array while declaration.

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

C# Jagged Array Example 2

Let's see a simple example of jagged array which initializes the jagged arrays upon declaration.

1. public class JaggedArrayTest
2. {
3.     public static void Main()
4.     {
5.         int[][] arr = new int[]{
6.         new int[] { 11, 21, 56, 78 },
7.         new int[] { 2, 5, 6, 7, 98, 5 },
8.         new int[] { 2, 5 }
9.         };
10.
11.         // Traverse array elements
12.         for (int i = 0; i < arr.Length; i++)
13.         {
14.             for (int j = 0; j < arr[i].Length; j++)
15.             {
16.                 System.Console.Write(arr[i][j]+" ");
17.             }
18.             System.Console.WriteLine();
19.         }
20.     }
21. }

Output:

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