In C#, the jagged array is referred to as an "array of arrays", where each item in the primary array is, in fact, an array. The size of each item within the jagged array can vary. Jagged arrays hold arrays instead of individual values. In contrast to multidimensional arrays, jagged arrays allow for inner arrays with varying lengths, providing greater versatility in element storage. This feature enhances efficiency when dealing with irregular data structures.
Simple Example:
Let's consider a basic illustration of a jagged array in C#, demonstrating the declaration, initialization, and traversal of jagged arrays.
Example
using System;
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[2][];// Declare the array
arr[0] = new int[] { 15, 25, 38, 45 };// Initialize the array
arr[1] = new int[] { 75, 28, 19, 41, 35, 39 };
// Traverse array elements
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
}
}
Output:
15 25 38 45
75 28 19 41 35 39
Here, we are going to explore the definition, setting values, and retrieval of elements in jagged arrays within C#.
Declaration of Jagged Array:
In a C# jagged array, it is only necessary to define the number of rows, while the column numbers are not specified. Adding the column numbers to the jagged array eliminates its jagged characteristic and transforms it into a multidimensional array. The declaration of a jagged array is denoted by two square brackets , signifying that it is an array comprised of arrays.
Here, the initial square bracket denotes the size of the primary array. Conversely, the subsequent bracket does not define the array dimensions; rather, it signifies that each element within the primary array is an additional array that may vary in length.
Syntax:
It has the following syntax:
Data-type[][] name_of_array = new data-type[rows][];
Let's demonstrate how to declare a jagged array using an example:
//declare the jagged array
int[][] arr = new int[2][];
In this example,
- int: It defines the data type of the array.
- : Square brackets represent the jagged array.
- arr: It represents the name of the jagged array.
- 2: It defines the number of arrays inside the jagged array.
Initialization of Jagged Array:
We have the flexibility to set the size of elements separately as each element in a jagged array is essentially an array itself. To illustrate, let's consider initializing a jagged array in C#.
//set the size of the first array as 4
arr[0] = new int[4];
//set the size of the first array as 4
arr[1] = new int[6];
Initialization and filling elements in the jagged array
In C#, there exist multiple techniques for initializing the array within the jagged array. A few of these methods include:
1. Using the Index Number:
Once the irregular array is set up in C#, we can use the index value to initialize it. This functionality allows us to dynamically set values for individual elements within the array by targeting their specific index positions.
Example:
Let's explore a scenario to demonstrate how we can set up the jagged array utilizing the Index value in C#.
Example
// Declare a jagged array with 2 rows
int[][] jagged_array = new int[2][];
// Initialize each row with a specific size
jagged_array[0] = new int[3]; // Initialize first row with 3 elements
jagged_array[1] = new int[2]; // Initialize second row with 2 elements
// Initialize the first array
jagged_array[0][0] = 4;
jagged_array[0][1] = 3;
jagged_array[0][2] = 7;
// Initialize the second array
jagged_array[1][0] = 2;
jagged_array[1][1] = 5;
- The index within the initial bracket indicates the position of the row within the jagged array.
- The index within the subsequent bracket indicates the position of the element within that particular row of the jagged array.
2. Initialize without defining the size of array elements:
When the size of a jagged array is unknown in advance, we can initialize its elements directly using inline initialization with specific values.
Example:
Let's explore an instance to demonstrate how we can set up the jagged array in C# without specifying the array size.
Example
// declaring an integer jagged array
int[][] arr = new int[2][];
// initializing each row with values
arr[0] = new int[4] { 11, 21, 56, 78 }; // First row
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 }; // Second row
3. Initialize while declaring Jagged Array:
In C# development, we have the option to directly employ array initializers for initializing a jagged array during its declaration. This feature enables us to define and fill the array simultaneously, enhancing code conciseness and clarity.
Example:
Let's explore an instance to demonstrate the process of initializing the array during the declaration of a jagged array in C#.
Example
int[][] jagged_array = {
new int[] {17, 24, 31, 42 } // First row (4 elements)
new int[] {18, 27, 16}; // Second row (3 elements)
new int[] {22, 15}; // Third row (2 elements)
};
A sample code demonstrating the implementation of a jagged array in the C# programming language.
Example
using System; // Importing the System namespace
public class C# Tutorial
{
public static void Main()
{
int[][] jaggedArr = new int[4][]; // Array Declaration
// Array Initialization
jaggedArr[0] = new int[] { 4, 2, 5, 9 }; // First row with 4 elements
jaggedArr[1] = new int[] { 8, 1, 7 }; // second row with 3 elements
jaggedArr[2] = new int[] { 6, 3, 2, 5 }; // third row with 4 elements
jaggedArr[3] = new int[] { 9, 4, 8, 1, 6 }; // fourth row with 5 elements
// Iterating the elements
for (int i = 0; i < jaggedArr.Length; i++)
{
Console.Write("Row " + i + ": "); // Printing row index
foreach (int num in jaggedArr[i])
Console.Write(num + " "); // Printing elements of the row
Console.WriteLine(); // Moving to the next line after printing a row
}
}
}
Output:
Row 0: 4 2 5 9
Row 1: 8 1 7
Row 2: 6 3 2 5
Row 3: 9 4 8 1 6
Explanation:
In this instance, we've defined a public class called C# Tutorial. Subsequently, a jaggedArr method is defined to create a jagged array with 4 elements, each capable of holding an array of integers. Initially, the inner arrays remain uninitialized. Subsequently, each element within the specified jagged array is initialized as an array of integers.
Following this, the external loop goes through each row of the jagged array. The internal foreach loop then goes through each item within the present row, displaying the elements with spaces in between. Finally, the console.WriteLine method shifts the cursor to the next line once all elements in the current row have been printed, guaranteeing that each row appears on its own line.
Example 2: Jagged Array upon declaration
Let's consider a basic illustration of the jagged array, where the jagged arrays are set up during declaration in C#.
Example
using System;
public class JaggedArrayTest
{
public static void Main()
{
// Declare and initialize a jagged array with 4 rows
int[][] arr = new int[4][]{
new int[] { 25, 45, 41, 78, 34 },
new int[] { 4, 52, 36, 15, 27, 73 },
new int[] { 2, 5, 28, 31, 47 },
new int[] { 13, 53, 72 }
};
// Iterate through each row of the jagged array
for (int i = 0; i < arr.Length; i++)
{
// Iterate through each element in the current row
for (int j = 0; j < arr[i].Length; j++)
{
// Print the current element followed by a space
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
}
}
Output:
25 45 41 78 34
4 52 36 15 27 73
2 5 28 31 47
13 53 72
Explanation:
In this instance, we are working with a JaggedArrayTest class. Following this, we initialize a jagged array with 4 elements during declaration, where each element is capable of containing an array of integers. Subsequently, the outer loop goes through each row of the jagged array.
The internal foreach loop cycles through each item within the present row, displaying the item delimited by spaces. Finally, the console.WriteLine method shifts the cursor to the next line once all the row's elements are printed, guaranteeing that each row appears on a distinct line.
Accessing and Modifying the Elements of a Jagged Array:
In C#, we have the ability to retrieve elements from jagged arrays by using two indices. The initial index pertains to the outer array (representing rows), while the subsequent index pertains to the inner array (representing columns).
//Accessing the first elements of a jagged array of a second row
int element = jaggedArray[1][0];
Conversely, we have the option to adjust the component of a jagged array by assigning a different value utilizing their indexes.
// Modify the second element of the first row to 15
jaggedArr[0][1] = 15;
Example:
Let's consider a scenario to demonstrate the process of accessing and altering elements in C#.
Example
using System;
public class C# Tutorial
{
static void Main(string[] args)
{
// Here is the declaration of a jagged array with 3 rows
int[][] arr = new int[3][];
// Here is the initialization of each row of the jagged array
arr[0] = new int[] { 5, 7, 8, 4}; // First row
arr[1] = new int[] { 3, 9, 12 }; // Second row
arr[2] = new int[] { 17, 19, 45, 16 }; // Third row
// Accessing the third element in the second row
int value = arr[1][2];
// Here, we are modifying the third element in
// the second row (from 12 to 15)
arr[1][2] = 15;
Console.WriteLine("Accessed Value: " + value); // Print the accessed value
Console.WriteLine("Modified Value: " + arr[1][2]); // Print the modified value
}
}
Output:
Accessed Value: 12
Modified Value: 15
Explanation:
In this instance, we are working with a class called C# Tutorial. Within this context, we define a jagged array named arr which consists of 3 rows. Each element within the arr structure is an array that may vary in length. Initialization of each row within the jagged array is done with a distinct value.
Afterward, we retrieve the third item in the second row which holds the data 12, and proceed to modify the previously accessed item from 12 to 15. Finally, the program displays the result in the console.
Jagged Arrays with Multidimensional Arrays
In C#, we can also make use of jagged arrays within multi-dimensional arrays to construct intricate data structures. To traverse a jagged array, we can employ nested loops. The outer loop moves through the rows, while the inner loop navigates through the elements within each row.
Syntax:
It has the following syntax:
//initializing 4 2-Dimensional array elements in 1-Dimensional array
int[][, ] jagged_array = new int[4][, ]
{
new int[, ] { {3, 4}, {2, 7}, {5, 8} },
new int[, ] { {18, 12}, {19, 22}, {35, 55} },
new int[, ] { {23, 54}, {26, 84}, {67, 37}, {49, 73} },
new int[, ] { {81, 32}, {5, 7}, {45, 94} },
};
Example:
Let's consider a scenario to showcase iterating through a jagged array within a multi-dimensional array in C#.
Example
using System;
public class MultiJaggedArray
{
public static void Main()
{
// Declare and initialize a jagged array where each element is a two-dimensional array
int[][,] jag_array = new int[4][,]
{
// First 2D array with 3 rows and 2 columns
new int[,] { {3, 4}, {2, 7}, {5, 8} },
// Second 2D array
new int[,] { {18, 12}, {19, 22}, {35, 55} },
// Third 2D array with 4 rows and 2 columns
new int[,] { {23, 54}, {26, 84}, {67, 37}, {49, 73} },
// Fourth 2D array
new int[,] { {81, 32}, {5, 7}, {45, 94} },
};
// Iterate through each 2D array in the jagged array
for (int i = 0; i < jag_array.Length; i++)
{
Console.WriteLine($"Elements of the Jagged Array {i+1}:");
// GetLength method takes an integer that indicates the array's dimension.
for (int j = 0; j < jag_array[i].GetLength(0); j++)
{
for (int k = 0; k < jag_array[i].GetLength(1); k++)
{
// Print the element at position [j, k] in the current 2D array
Console.Write("{0} ",jag_array[i][j, k]);
}
Console.WriteLine();
}
Console.WriteLine();
}
}
}
Output:
Elements of the Jagged Array 1:
3 4
2 7
5 8
Elements of the Jagged Array 2:
18 12
19 22
35 55
Elements of the Jagged Array 3:
23 54
26 84
67 37
49 73
Elements of the Jagged Array 4:
81 32
5 7
45 94
Explanation:
In this instance, we are examining a MultiJaggedArray class. Following that, we define a jagged array consisting of 4 elements, with each element being a two-dimensional array. Each element within the jagged array is set up with a two-dimensional array that varies in size.
To determine the dimensions of each 2D array, the GetLength(0) and GetLength(1) methods are employed to fetch the number of rows and columns correspondingly. Subsequently, a loop is executed to traverse through each row and column in order to retrieve and display the elements stored within.
C# Jagged Arrays MCQs
- How can we declare an integers jagged array with 3 rows in C#?
- int jaggedArray = new int2;
- int[,] jaggedArray = new int[2, ];
- int jaggedArray = new int[2];
- int jaggedArray = new int[2];
(a) Initializing a jagged array of integers with 2 rows and unspecified column lengths.
- Predict the output of the code snippet provided above.
int[][] jaggedArray = new int[2][];
jaggedArray[0] = new int[] {2, 15, 27};
jaggedArray[1] = new int[] {10, 24};
Console.WriteLine(jaggedArray[1][1]);
- What is the default value of an uninitialized element in a jagged array of integers in C#?
- Null
- Undefined
- How do we initialize a jagged array with different row lengths in C#?
- By using a multidimensional array.
- It is not possible to have row of different lengths.
- By declaring a single dimensional array.
- By specifying the length of every row individually.
- What is the following option is true about the jagged arrays?
- Jagged arrays are an array of arrays that allow every inner array to have different lengths.
- Jagged arrays are known as single-dimensional arrays.
- Jagged arrays are multidimensional arrays with fixed row sizes.
- Jagged arrays cannot contain arrays as elements.
(a) Jagged arrays are arrays composed of arrays that enable each inner array to have varying lengths.