A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an “array of arrays.” The following examples show how to declare, initialize, and access jagged arrays.
You have several rows of data, such as integers, and want to store them together in a single data structure. Jagged arrays are ideal for this.
A jagged array is declared by placing one pair of opening and closing brackets after another. With the initialization of the jagged array, only the size that defines the number of rows in the first pair of brackets is set. The second brackets that define the number of elements inside the row are kept empty because every row has a different number of elements.
The jagged array that i am working now contains three rows where the first row has two elements, the second row has six elements, and the third row has three elements. Got it!!
Jagged array looping is much [faster] than 2D array looping.
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 30 31 32 33 | int[][] jagged = new int[3][]; //Jagged Aray Declaration jagged[0] = new int[2] { 1, 2 }; jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 }; jagged[2] = new int[3] { 9, 10, 11 }; // So now lets use a for loop to iterate through the jagged array. <pre lang="csharp" line="1"> for (int row = 0; row <jagged.Length; row++) { for (int element = 0; element <jagged[row].Length; element++) { Console.WriteLine( "row: {0}, element: {1}, value: {2}", row, element, jagged[row][element]); } } // OUTPUT // ======== row: 0, element: 0, value: 1 row: 0, element: 1, value: 2 row: 1, element: 0, value: 3 row: 1, element: 1, value: 4 row: 1, element: 2, value: 5 row: 1, element: 3, value: 6 row: 1, element: 4, value: 7 row: 1, element: 5, value: 8 row: 2, element: 1, value: 9 row: 2, element: 2, value: 10 row: 2, element: 3, value: 11 |