Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to find the length of jagged array using a property?
A jagged array in C# is an array of arrays where each inner array can have different lengths. To find the length of a jagged array, you use the Length property, which returns the number of inner arrays (rows) in the jagged array.
Syntax
Following is the syntax for declaring a jagged array −
dataType[][] arrayName = new dataType[size][];
To get the length of a jagged array, use the Length property −
int numberOfRows = arrayName.Length;
Using Length Property
The Length property returns the number of rows (outer arrays) in the jagged array −
using System;
public class Program {
public static void Main() {
int[][] arr = new int[][] {
new int[] {0, 0},
new int[] {1, 2},
new int[] {2, 4},
new int[] {3, 6},
new int[] {4, 8}
};
Console.WriteLine("Number of rows: " + arr.Length);
Console.WriteLine("Length of first row: " + arr[0].Length);
Console.WriteLine("Length of second row: " + arr[1].Length);
}
}
The output of the above code is −
Number of rows: 5 Length of first row: 2 Length of second row: 2
Jagged Array with Different Row Lengths
Here's an example showing a jagged array where each row has different lengths −
using System;
public class Program {
public static void Main() {
int[][] jaggedArray = new int[][] {
new int[] {1},
new int[] {2, 3},
new int[] {4, 5, 6},
new int[] {7, 8, 9, 10}
};
Console.WriteLine("Total rows: " + jaggedArray.Length);
for (int i = 0; i < jaggedArray.Length; i++) {
Console.WriteLine("Row " + i + " length: " + jaggedArray[i].Length);
Console.Write("Elements: ");
for (int j = 0; j < jaggedArray[i].Length; j++) {
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
}
}
The output of the above code is −
Total rows: 4 Row 0 length: 1 Elements: 1 Row 1 length: 2 Elements: 2 3 Row 2 length: 3 Elements: 4 5 6 Row 3 length: 4 Elements: 7 8 9 10
Additional Array Properties
Besides Length, jagged arrays support other useful properties and methods −
using System;
public class Program {
public static void Main() {
int[][] arr = new int[][] {
new int[] {0, 0},
new int[] {1, 2},
new int[] {2, 4},
new int[] {3, 6},
new int[] {4, 8}
};
Console.WriteLine("Length: " + arr.Length);
Console.WriteLine("Upper Bound: " + arr.GetUpperBound(0));
Console.WriteLine("Lower Bound: " + arr.GetLowerBound(0));
Console.WriteLine("Dimensions of Array: " + arr.Rank);
}
}
The output of the above code is −
Length: 5 Upper Bound: 4 Lower Bound: 0 Dimensions of Array: 1
Conclusion
The Length property of a jagged array returns the number of rows (outer arrays) it contains. Each individual row can have its own length, which you can access using arrayName[index].Length. This flexibility makes jagged arrays useful when you need arrays of varying sizes.
