I am trying to figure out what is the usefulness of jagged arrays? I mean is there any applications of jagged arrays in real life situations ? any suggestions will be appreciated
-
Performance is usually better for jagged arrays. – CodesInChaos Nov 10 '13 at 10:56
-
Pascal's triangle is a good example for using jagged arrays. – Nikolay Kostov Sep 20 '19 at 09:12
3 Answers
What counts as a "real life situation"? One example that immediately comes to mind is storing sparse matrices. A matrix is typically stored as a 2D array in what as known as a "dense" representation. It's called dense because it stores each and every element of the array. But in some cases many elements of the array are 0 (or perhaps some other value) and it doesn't make sense to store them explicitly. Granted a lot of sparse matrix representations use a small number of 1D arrays.
Really jagged arrays are definitely useful in situations where you don't want each 1D array to have the same length. Jagged arrays also make it somewhat easier to swap out entire "rows".
It should be noted that, in .NET at least, that jagged arrays usually have better performance than multidimensional arrays.
If you care about speed then you always prefer jagged arrays over multi-dimensional arrays. The .NET runtime support (jitter and CLR) makes a strong distinction between vectors and arrays. A vector is a special case of an array, one dimension with the starting index at 0. It is very heavily optimized inside the CLR, pulling every possible trick. And the jitter, giving strong odds for array bounds checking elimination.
A jagged array is a vector of vectors, you get all of the runtime optimizations when you use them. Multi-dimensional arrays don't. The speed difference is about a factor of two.
Only ever consider using multi-dimensional arrays if you favor the syntax convenience and have verified that array indexing is not on your program's critical path.

- 1
- 1

- 922,412
- 146
- 1,693
- 2,536
Here is a simple example:
Let's say for some reason you need to factorise integers. For small integers it might make sense to create a lookup table in order to speed things up. That would be a jagged array.
int[][] factors = new int[][]
{
null, // 0 doesn't have prime factors
new int[] { }, // 1 is the trivial case
new int[] { 2 },
new int[] { 3 },
new int[] { 2, 2 },
new int[] { 5 },
new int[] { 2, 3},
new int[] { 7 },
new int[] { 2, 2, 2 },
new int[] { 3, 3 },
new int[] { 2, 5 },
// ... and so on
};
int[] PrimeFactorsOf(int value)
{
if (value < factors.Length)
{
return factors[value];
}
else
{
// do the work
}
}

- 3,393
- 18
- 28