Jagged Arrays in C#

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!!


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 i am using for loop to iterate through the jagged array.

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]);
}
}


NOW THE OUTPUT WILL BE LIKE THIS.
==================================

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

Your input is appreciated.

Bindu


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: