Jagged array is another type of an array in C#,. A Jagged can be defined as an array which consists of another array in it. Jagged Array provides us flexibility of creating different size of rows.
Arrays which have elements of the same size are called rectangular arrays while arrays which have elements of different size are called jagged arrays.
Jagged array is declared using two square brackets ([] []), following are the ways to declare jagged array:
int[ ][ ] intJaggedArr = new int[2][ ]; // int jagged array, which will have 2 rows and arrays
string[][] jaggedArrayStr = new string[5][]; //string jagged array
In the above intJaggedArray
sample, the first array size ,i.e, 2 in the above example and the second bracket specifies the dimension of the array which is going to be stored as values.
A jagged array can store multiple arrays with different lengths. We can declare an array of length 2 and another array of length 5 and both of these can be stored in the same jagged array.
intJaggedArr [0] = new int[5] { 1, 4, 5, 6, 7 }; //array of size 5
intJaggedArr [1] = new int[3] { 1, 2, 3 }; //array of size 3
Considering above example, we can have two arrays inside intJaggedArr
, as declared above, and we saved two int
type arrays inside it.
using System;
public class JaggedArrayProgram
{
public static void Main()
{
//declare and initilize jagged array
int[][] myJaggedArray = new int[2][];
//fill jagged array with another array
myJaggedArray[0] = new int[3]{1, 2, 3};
myJaggedArray[1] = new int[2]{4, 5 };
//prinint jagged values by using Index Locations
Console.WriteLine(myJaggedArray[0][0]); // 1
Console.WriteLine(myJaggedArray[0][1]); // 2
Console.WriteLine(myJaggedArray[0][2]); // 3
Console.WriteLine(myJaggedArray[1][0]);//4
Console.WriteLine(myJaggedArray[1][1]); // 5
}
}
Output
1
2
3
4
5
Let's take a look on another C# Jagged example, in which we will be looping through the values of jagged array.
using System;
public class JaggedArraySampleProgram
{
public static void Main()
{
string[][] jaggedArrayStr = new string [2][] {
new string[] {"C#", "Java"},
new string[] {"C", "C++", "Objective-C"}
};
// traverse value from each array element
for (int i = 0; i < jaggedArrayStr.Length; i++) {
for (int j = 0; j < jaggedArrayStr[i].Length; j++) {
Console.Write(jaggedArrayStr[i][j]+ " ");
}
//new row, new line added
Console.WriteLine();
}
}
}
Output
C# Java
C C++ Objective-C
In the above example, we are using jaggedArrayStr.Length
method to get size of main array and jaggedArrayStr[i].Length
to get size of inner array present inside jagged array.
So, first loop, traverse the jagged array, while second loop traverse the array inside jagged array, printing elements value at the same time.