Jagged Arrays C# Help

A 2-dimensional array has a rectangular size (for example, 3 x 3 elements). A jagged array is more flexible in sizing the array. With a jagged array every row can have a different size.

It contrasts a 2-dimensional array that has 3 x 3 elements with a jagged array. The jagged array shown contains three rows where the first row has two elements, the second row has six elements, and the third row has three elements.

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. Next, the element number of the rows can be set for every row:

Iterating through all elements of a jagged array can be done with nested for loops. In the outer for loop every row is iterated, and the inner for loop iterates through every element inside a row.

The outcome of the iteration displays the rows and every element within the rows:

row: O. element: O. value: 1
row: O. element: 1. value: 2
row: 1. element: O. 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

Posted on October 28, 2015 in Arrays

Share the Story

Back to Top
Share This