C# Jagged Arrays

A jagged array is an array of arrays, where each inner array can have a different length. This allows for storage of data structures that are not rectangular.

Key Topics

1. Declaring Jagged Arrays

Example: Creating a Jagged Array

// Declare a jagged array with 3 elements
int[][] jaggedArray = new int[3][];

// Initialize the jagged array
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6 };

2. Accessing Elements

Example: Reading an Element

Console.WriteLine("Element at [1][2]: " + jaggedArray[1][2]);  // Outputs 5

3. Iterating Through Jagged Arrays

Example: Nested Loops for Jagged Arrays

Console.WriteLine("Jagged Array Elements:");
for (int i = 0; i < jaggedArray.Length; i++)
{
    for (int j = 0; j < jaggedArray[i].Length; j++)
    {
        Console.Write(jaggedArray[i][j] + " ");
    }
    Console.WriteLine();
}

Output:

Jagged Array Elements:
1 2
3 4 5
6

Key Takeaways

  • Jagged arrays are arrays of arrays with varying lengths.
  • Elements are accessed using two sets of square brackets.
  • They are useful for representing non-rectangular data structures.
  • Nested loops help in iterating through jagged arrays.