Hello. Let me tell you about Jagged Arrays today.
What is a jagged array?
A jagged array is an array of arrays where each inner array can have a different length. In C#, jagged arrays provide flexibility in working with multidimensional data structures where the dimensions can be variable.
Creating a jagged array
To create a jagged array in C#, use the following syntax:
// Create a jagged array with 3 inner arrays
int[][] jaggedArray = new int[3][];
This code creates a jagged array with 3 inner arrays, but the length of the inner arrays is not yet defined.
Initializing the inner arrays
Each inner array can be initialized with a different length:
jaggedArray[0] = new int[5]; // First inner array of 5 elements
jaggedArray[1] = new int[3]; // Second inner array of 3 elements
jaggedArray[2] = new int[4]; // Third inner array of 4 elements
Setting values
Element values can be set like this:
jaggedArray[0][0] = 1;
jaggedArray[0][1] = 2;
jaggedArray[1][0] = 10;
jaggedArray[1][1] = 20;
jaggedArray[2][0] = 100;
Printing Elements
To print all the elements of a jagged array, use the following code:
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
This code loops through each inner array and prints its elements to the screen.
Summary
- Jagged Array: An array of arrays with the ability to have varying lengths of inner arrays.
- Flexible: Each inner array can have a different length.
- Memory Efficient: Memory is allocated only as needed for each inner array.
Jagged arrays are useful when you need to work with data whose structure has a variable length.
Top comments (0)