Jagged Arrays are also known as “array of arrays” that is because the elements are arrays themselves. Their dimensions and sizes may be different.
Declaration of jagged array in C#.
Jagged array can be declared and created in a following way.
1 2 3 4 5 | //declaration int [][] marks; //creating to allocate memory int[][] marks = new int[5][]; |
Initialization of Jagged array in C#
As told above, a jagged array can be a different size. As the elements inside the arrays are the arrays themselves so they may vary in dimension. Let us see an example.
You can initialize array in different ways, one of which is:
1 2 3 4 5 | //Initializing in single line int[][] marks = new int[2][]{ new int[]{88,90,60}, new int[]{45,80,55,92} }; |
As you can see, we initialize it in a single line with a new
operator for each array element with a different dimension. One has 3 integers while the other have 4 integers.
You can also separately initialize them with index number such as:
1 2 | marks[0] = new int[3] { 88,90,60 }; marks[1] = new int[4] { 45,80,55,92 }; |
Let us understand with an example:
C# program illustrates using a jagged array
Nested for loop is used to traverse through jagged array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using System; namespace Arrays { class JaggedArrays { static void Main(string[] args) { //jagged arrays initialization int[][] arr = new int[][] { new int[] { 0, 1 }, new int[] { 2, 3 }, new int[] { 4, 5 }, new int[] { 6, 7 } }; //displaying for (int i = 0; i < 4; i++) for (int j = 0; j < 2; j++) Console.WriteLine("arr[{0}][{1}] = {2}", i, j, arr[i][j]); } } } |
Output:
1 2 3 4 5 6 7 8 | arr[0][0] = 0 arr[0][1] = 1 arr[1][0] = 2 arr[1][1] = 3 arr[2][0] = 4 arr[2][1] = 5 arr[3][0] = 6 arr[3][1] = 7 |