Jagged Arrays in C# using example
- By Gurunatha Dogi in C#
- Apr 22nd, 2013
- 24305
- 0
Definition of Jagged Arrays
"Array of arrays" is called jagged array. A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes.
In jagged array the length of each array index can differ.
Jagged arrays, can store efficiently many rows of varying lengths.
Syntax of jagged arrays in C#
static void Main(string[] args){ //Syntax of Jagged Array int[][] jaggedarray = new int[3][]; }
Syntax of a jagged array starts with data type ("int") followed by two square braces ([] []) then array name ("jaggedarray") and reference it to same data type with number of rows (declare it in first square braces otherwise it will throw an error).
Now using the jagged array variable ("jaggedarray") lets do initialization.
So our jagged array variable got length of 3 rows to initialize it.
Initialization Process of Jagged Array
//Initialization of a Jagged Array jaggedarray[0] = new int[5] { 99, 999, 49, 79, 59 }; jaggedarray[1] = new int[3] { 199, 1999, 149 }; jaggedarray[2] = new int[1] { 999 };
So we have initialized the jagged array i.e. on index 0 of jagged array we initialized new array of size of 5 with integer data type and assigned the values to it respectively
Same way we also initialized index 1 and index 2 of jagged array as shown in above code.
Now lets display the output
To display output we will use "FOR Loop" to loop through the actual length of an array as shown below snippet of code.
for (int i = 0; i < jaggedarray.Length; i++){ …. }
Since jagged array is array of array so we need to loop it again the each loop of "For Loop" by using "For-Each Loop" because every row of jagged array initialized with new array of different sizes.
Lets display the output
for (int i = 0; i < jaggedarray.Length; i++){ foreach (int j in jaggedarray[i]){ Console.WriteLine("Displaying Jagged Array For Row{0} value {1}", i, j); } }
As you can see we have nested loop (loop inside loop) because every row of jagged array initialized with new array of different sizes.
Output
Gurunatha Dogi
Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more
Add a Comment

- By Gurunatha Dogi
- Apr 19th, 2013
- 54906
- 0
Abstract Class and Abstract Method With An Example Using C#

- By Gurunatha Dogi
- Apr 17th, 2013
- 181174
- 0
OOPS Principle - Abstraction in C# with an example and explanation

- By Gurunatha Dogi
- Apr 16th, 2013
- 26212
- 0
What are Delegates in C# - Step By Step Creating and Using the Delegate

- By Gurunatha Dogi
- Nov 19th, 2012
- 31993
- 0