Jagged Array in C#

In C#, a jagged array is an array of arrays. Unlike rectangular (multidimensional) arrays, jagged arrays allow each element of the outer array to be an array of different lengths. This flexibility makes jagged arrays useful for representing irregular data structures where the inner arrays can have varying sizes. Each row (dimension) has a different length or size in jagged arrays, but in a multidimensional array, each row (dimension) has fixed or the same length because because each row is essentially a separate array.
Let's look it with Jagged array in C#
// Jagged array declaration
int[][] jaggedIntArray = new int[3][];
// Initialize jagged array
jaggedIntArray[0] = new int[] { 1, 2, 3 };
jaggedIntArray[1] = new int[] { 4, 5, 6, 7 };
jaggedIntArray[2] = new int[] { 8, 9 };
// Access elements
Console.WriteLine(jaggedIntArray[0][0]); // Output: 1
Console.WriteLine(jaggedIntArray[1][2]); // Output: 6
Console.WriteLine(jaggedIntArray[2][1]); // Output: 9
This example of a jagged array features rows of varying lengths, with the first row containing 3 elements, the second row containing 4 elements, and the third row containing 2 elements.
Now, let's look at a multidimensional array example in C#:
// Jagged array declaration
int[][] jaggedIntArray = new int[3][];
// Initialize jagged array
jaggedIntArray[0] = new int[] { 1, 2, 3 };
jaggedIntArray[1] = new int[] { 4, 5, 6, 7 };
jaggedIntArray[2] = new int[] { 8, 9 };
// Access elements
Console.WriteLine(jaggedIntArray[0][0]); // Output: 1
Console.WriteLine(jaggedIntArray[1][2]); // Output: 6
Console.WriteLine(jaggedIntArray[2][1]); // Output: 9
In this example of a multidimensional array, every row needs to be of same length (in this example, 3). All rows contain the same quantity of elements, and you use two indices to access elements, indicating the row and column.
Declaration of Jagged array :
In below example i have declared integer type jagged array. In this integer type jagged array 1st dimension has fixed size which is 3 and each one (dimension) capable of holding an array of integers. But the size of each array can be different. This structure allows for a dynamic allocation of memory, accommodating different lengths of arrays within the jagged array.
Example
// Declare a jagged array with 3 inner arrays
int[][] jaggedArray = new int[3][];
Initialization of Jagged array:
In below example we initializes the 1st element of jaggedArray with an inner array of three ineteger elements 1,2,3.We initializes the 2nd element of jaggedArray with an inner array of two elements 4,5. We initializes the 3rd element of jaggedArray with an inner array of four elements 6,7,8,9.
Example
// Initialize the inner arrays
jaggedArray[0] = new int[] { 1, 2, 3 }; // First inner array with 3 elements
jaggedArray[1] = new int[] { 4, 5 }; // Second inner array with 2 elements jaggedArray[2]
= new int[] { 6, 7, 8, 9 }; // Third inner array with 4 elements
Accessing elements of Jagged array:
In below example we accessing the element at the first inner array's first position. Accessing the element at the second inner array's second position.Similarly, accessing the element at the third inner array's third position.
Example
int element = jaggedArray[1][0];
// Accessing the element at the first inner array's first position int element = jaggedArray[2][1];
// Accessing the element at the second inner array's second position int element = jaggedArray[3][1];
// Accessing the element at the third inner array's third position
Iterating Through a Jagged Array:
This is syntax for Iterating through a Jagged Array. In below example we have used two for loop for iterating over jagged array and accessing the elements of jagged array.
Example
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int j = 0; j < jaggedArray[i].Length; j++)
{
int element = jaggedArray[i][j]; Console.Write(element + " ");
}
Console.WriteLine();
}
Jagged Array in C# with Example
using System;
public class Program
{
public static void Main(string[] args)
{
int[][] mangoPrices = new int[2][];
// Declare the array
mangoPrices[0] = new int[] { 101, 201, 506, 708 };
// Initialize the array
mangoPrices[1] = new int[] { 402, 601, 307, 401, 509, 603 };
// Iterating array elements
for (int i = 0; i < mangoPrices.Length; i++)
{
for (int j = 0; j < mangoPrices[i].Length; j++)
{
Console.Write(mangoPrices[i][j]+" ");
}
Console.WriteLine();//new line at each row
}
}
}
Output
101, 201, 506, 708
402, 601, 307, 401, 509, 603
When we use Jagged Array?
Jagged arrays are mostly used when we need to represent data structures with different lengths for each dimension, such as when dealing with irregular matrices, trees, or collections of variable-length sequences. They offer flexibility in memory usage and are suitable for scenarios where the data structure doesn't fit neatly into rectangular shapes like traditional multidimensional arrays.
Where we use Jagged Array?
Jagged arrays are used in various scenarios where the data structure requires flexibility in the lengths of its dimensions. Some common use cases include:
Representing matrices with varying row lengths.Storing data structures like trees, where each node can have a different number of child nodes.Managing collections of variable-length sequences, such as lists of sentences with different numbers of words.In general, jagged arrays are useful whenever a multidimensional array with varying lengths for each dimension is needed.
Advantages of Jagged Array?
The advantages of using jagged arrays in C# include:
1. Memory Efficiency:
Jagged arrays consume less memory compared to rectangular multidimensional arrays when the dimensions vary significantly. This is because each "row" is a separate array, allowing for flexibility in memory allocation.
2. Flexibility:
Jagged arrays allow for varying lengths of sub-arrays, providing flexibility in representing irregular data structures. This is particularly useful in scenarios where the structure of the data is not uniform across dimensions.
3. Performance:
Jagged arrays are more efficient than multidimensional arrays for accessing elements, particularly when dimensions vary greatly. Jagged arrays store references to separate arrays for each row, helping to reduce cache misses and improve locality of reference.
4. Ease of Initialization:
Jagged arrays can be easily initialized with different lengths for each row, making them convenient for scenarios where the structure of the data is known at runtime.
5. Simpler Iteration:
Iterating through a jagged array can be done easily through nested loops, where each loop represents a unique dimension. This approach often results in code that is easier to read and maintain compared to working with multidimensional arrays.
Disadantages of Jagged Array?
While jagged arrays in C# offer several advantages, they also come with some disadvantages:
1. Memory Overhead:
Jagged arrays consume more memory compared to rectangular multidimensional arrays when the dimensions are relatively uniform. This is because they require additional memory to store references to each sub-array.
2. Potential Fragmentation:
As jagged arrays consist of individual arrays for each row, memory fragmentation may occur, particularly if the sub-arrays have different sizes. This could result in inefficient memory usage and possible performance problems.
3. Complexity:
Using jagged arrays can be more challenging than rectangular multidimensional arrays, especially with nested arrays of varying lengths. Extra caution and error handling are needed when managing and accessing elements.
4. Less Efficient Random Access:
Accessing elements in a jagged array randomly (i.e., not through sequential iteration) can be less efficient compared to rectangular multidimensional arrays. This is because jagged arrays involve accessing multiple levels of references before reaching the desired element.
5. Potential Performance Overhead:
While jagged arrays can offer performance benefits in certain scenarios, they may also incur overhead in terms of memory allocation and access time, especially if the dimensions vary widely and require frequent resizing of sub-arrays.
Summary
Jagged arrays are particularly useful when you have data with irregular or varying dimensions, such as representing rows of a table where each row has a different number of columns or when working with data structures that naturally have varying sizes for different elements.
For more useful tutorials about c# click here: C-Sharp Tutorial
Subscribe to my newsletter
Read articles from Shahzad Aslam directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
