This content originally appeared on DEV Community and was authored by Kerimova_Manzura
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.
This content originally appeared on DEV Community and was authored by Kerimova_Manzura
Kerimova_Manzura | Sciencx (2024-09-10T14:37:58+00:00) Jagged Arrays in C#. Retrieved from https://www.scien.cx/2024/09/10/jagged-arrays-in-c/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.