In this article we learn what a jagged array is and how we use jagged arrays in our applications.
A jagged array is an array of arrays.
Problem
Suppose I run an institute and I have 4 students and all 4 students have enrolled in 2 courses.
Let's make a table for better visualization.
Student Name Subject Name.
Student Name |
Subject Name |
Pramod |
C# SQL Server Java jQuery |
Ravi |
C# |
Rahul |
Android Window Phone Development iOS development |
Deepak |
Html5 CSS3 |
Solution
We can do this to use a jagged array.
First create a string array to store student names.
- string[] studentArray = new string[4];
- studentArray[0] = "Pramod";
- studentArray[1] = "Ravi";
- studentArray[2] = "Rahul";
- studentArray[3] = "Deepak";
We want 4 string arrays so we specified the size of our jagged array as 4.
- string[][] jaggedArray = new string[4][];
Let's specify the size of the first string array within jagged array as 4.
- jaggedArray[0] = new string[4];
For the second, third and fourth string array length in jagged array is 1,3,2 respectively.
- jaggedArray[1] = new string[1];
- jaggedArray[2] = new string[3];
- jaggedArray[3] = new string[2];
Let's store some data in the jagged array.
- jaggedArray[0][0] = "C#";
- jaggedArray[0][1] = "SQL Server";
- jaggedArray[0][2] = "Java";
- jaggedArray[0][3] = "jQuery";
-
- jaggedArray[1][0] = "C#";
-
- jaggedArray[2][0] = "Android";
- jaggedArray[2][1] = "Window Phone Development";
- jaggedArray[2][2] = "iOS development";
-
- jaggedArray[3][0] = "Html5";
- jaggedArray[3][1] = "CSS3";
Let's print this using the following code.
- for (int i = 0; i < jaggedArray.Length; i++)
- {
- string[] anotherArray =jaggedArray[i];
- Console.WriteLine(studentArray[i]);
- Console.WriteLine();
- for (int j = 0; j < anotherArray.Length; j++)
- {
- Console.WriteLine(anotherArray[j]);
- }
- Console.WriteLine("=========================");
- }
- Console.ReadLine();
Output