Home »
.Net
What is Jagged Array in C#?
Learn: What is jagged array in C#, how jagged arrays are declared, how to access elements, how to read and print elements through jagged array?
We have discussed about One Dimensional arrays and Two Dimensional arrays in C#.Net, and we know that in two dimensional arrays, each row has some number of elements but all rows will have same number of elements. In this post we are going to learn about Jagged Array, which are not supported by C++ programming language.
A jagged array is special type of multidimensional array that has the irregular dimensions’ sizes. Every row has different number of elements in it.
Declaration of jagged array:
<data_type>[][] variable = new <data_type> [row_size][];
Example:
int[][] X = new int[2][];
X[0] = new int [4];
X[1] = new int [6];
Initialization of jagged array:
int[][] X = new int[][] {new int[] {1, 2, 3}, new int[] {4,5, 6, 7}};
An example of jagged array in C#
using System;
namespace arrayEx
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int j = 0;
int[][] X = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 } };
Console.Write("\n\nElements are: \n");
for (i = 0; i < X.GetLength(0); i++)
{
for (j = 0; j < X[i].Length; j++)
{
Console.Write(X[i][j] + " ");
}
Console.WriteLine();
}
}
}
}
Output
Elements are:
1 2 3
4 5 6 7
Press any key to continue . . .
In above example Jagged array X contains 3 elements in first row and 4 elements in second row.