C# Jagged Array
A jagged array is an array whose elements are arrays. Unlike a rectangular array where all the rows have the same length, in a jagged array, each row can have a different length.
This provides more flexibility but requires more memory management.
Example of an jagged array in C#.
using System;
class Program
{
static void Main()
{
// Declare a jagged array with three "rows"
int[][] jaggedArray = new int[3][];
// Initialize each "row" with a different length
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5, 6, 7 };
jaggedArray[2] = new int[] { 8, 9 };
// Access and print 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();
}
}
}
In this example, jaggedArray
is a jagged array with three rows, where each row is an array of integers. The lengths of these arrays can be different.
The nested loops iterate over the elements of the jagged array and print them to the console.
Jagged arrays are useful when you need a data structure that can have varying row lengths, and they provide more flexibility than rectangular arrays in such scenarios.