Okay, accessing a value in a jagged array in C# requires using multiple sets of square brackets [], one for each level of the array.
Remember, a jagged array is an array of arrays. So, you first specify the index for the outer array (to select which inner array you want) and then specify the index for the inner array (to select the element within that inner array).
Syntax:
jaggedArray[indexOfOuterArray][indexOfInnerArray]
Example:
Let's say you have the following jagged array:
using System;
public class JaggedArrayExample
{
public static void Main(string[] args)
{
// Declare and initialize a jagged array
// It has 3 inner arrays with different lengths
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[2] { 10, 11 }; // First inner array (index 0) has 2 elements
jaggedArray[1] = new int[4] { 20, 21, 22, 23 }; // Second inner array (index 1) has 4 elements
jaggedArray[2] = new int[3] { 30, 31, 32 }; // Third inner array (index 2) has 3 elements
// --- Accessing Values ---
// Access the first element (value 10) of the first inner array (index 0)
int value1 = jaggedArray[0][0];
Console.WriteLine($"jaggedArray[0][0] = {value1}"); // Output: jaggedArray[0][0] = 10
// Access the third element (value 22) of the second inner array (index 1)
int value2 = jaggedArray[1][2];
Console.WriteLine($"jaggedArray[1][2] = {value2}"); // Output: jaggedArray[1][2] = 22
// Access the last element (value 32) of the third inner array (index 2)
int value3 = jaggedArray[2][2];
Console.WriteLine($"jaggedArray[2][2] = {value3}"); // Output: jaggedArray[2][2] = 32
// You can also access an entire inner array
int[] firstInnerArray = jaggedArray[0];
Console.WriteLine($"First inner array's first element: {firstInnerArray[0]}"); // Output: First inner array's first element: 10
// --- Iterating Example ---
Console.WriteLine("\nIterating through the jagged array:");
// Outer loop iterates through the inner arrays
for (int i = 0; i < jaggedArray.Length; i++)
{
// Inner loop iterates through elements of the current inner array
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write($"{jaggedArray[i][j]} ");
}
Console.WriteLine(); // New line after each inner array
}
}
}
Explanation:
jaggedArray[0] selects the first inner array (new int[2] { 10, 11 }).
jaggedArray[0][0] then selects the element at index 0 within that first inner array, which is 10.
jaggedArray[1] selects the second inner array (new int[4] { 20, 21, 22, 23 }).
jaggedArray[1][2] selects the element at index 2 within that second inner array, which is 22.
You use [outerIndex][innerIndex] for each value you want to retrieve.