Introduction
C# is a multi-paradigm, general programming language. C# was designed by Anders Hejlsberg in 2000. Later it was introduced by Microsoft along with the .NET framework and Visual Studio.
The array is nothing but a collection of elements of a similar data type. Each element stored in an array can be accessed easily using only the index of the element.
A jagged array can be defined as a collection of two or more arrays of similar data types, such that each array in a Jagged array may or may not be of the same size. We can even add multi-dimensional arrays in Jagged arrays.
One-Dimensional Jagged Array
A one-dimensional jagged array is a collection of two or more one-dimensional arrays of the same data type. We can declare a jagged array using the following syntax,
Direct Method
int[][] jag_arr = new int[][]
{
new int[] {1, 5, 7, 9},
new int[] {10, 25, 90},
new int[] {15, 2},
new int[] {1, 10, 5, 0, 50}
};
Short Hand Method
int[][] jag_arr =
{
new int[] {1, 5, 7, 9},
new int[] {10, 25, 90},
new int[] {15, 2},
new int[] {1, 10, 5, 0, 50}
};
Example
Now, let us look at an example code of a one-dimensional jagged array.
using System;
class JaggedArray {
public static void Main()
{
int[][] jag_arr =
{
new int[] {1, 5, 7, 9},
new int[] {10, 25, 90},
new int[] {15, 2},
new int[] {1, 10, 5, 0, 50}
};
for (int n = 0; n < jag_arr.Length; n++) {
System.Console.Write("Row({0}): ", n);
for (int k = 0; k < jag_arr[n].Length; k++) {
System.Console.Write("{0} ", jag_arr[n][k]);
}
System.Console.WriteLine();
}
}
}
In the above code, we created a jagged array using the shorthand method and then used a for loop to print all the elements present in the jagged array.
Also see, Introduction to C++