What a Jagged Array Is

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.

  1. string[] studentArray = new string[4];  
  2. studentArray[0] = "Pramod";  
  3. studentArray[1] = "Ravi";  
  4. studentArray[2] = "Rahul";  
  5. studentArray[3] = "Deepak";  
We want 4 string arrays so we specified the size of our jagged array as 4.
  1. string[][] jaggedArray = new string[4][];  
Let's specify the size of the first string array within jagged array as 4.
  1. jaggedArray[0] = new string[4];  
For the second, third and fourth string array length in jagged array is 1,3,2 respectively.
  1. jaggedArray[1] = new string[1];  
  2. jaggedArray[2] = new string[3];  
  3. jaggedArray[3] = new string[2];  
Let's store some data in the jagged array.
  1. jaggedArray[0][0] = "C#";  
  2. jaggedArray[0][1] = "SQL Server";  
  3. jaggedArray[0][2] = "Java";  
  4. jaggedArray[0][3] = "jQuery";  
  5.   
  6. jaggedArray[1][0] = "C#";  
  7.   
  8. jaggedArray[2][0] = "Android";  
  9. jaggedArray[2][1] = "Window Phone Development";  
  10. jaggedArray[2][2] = "iOS development";  
  11.   
  12. jaggedArray[3][0] = "Html5";  
  13. jaggedArray[3][1] = "CSS3";  
Let's print this using the following code.
  1. for (int i = 0; i < jaggedArray.Length; i++)  
  2. {  
  3.       string[] anotherArray =jaggedArray[i];  
  4.       Console.WriteLine(studentArray[i]);  
  5.       Console.WriteLine();  
  6.       for (int j = 0; j < anotherArray.Length; j++)  
  7.       {  
  8.             Console.WriteLine(anotherArray[j]);  
  9.       }  
  10.       Console.WriteLine("=========================");  
  11. }  
  12. Console.ReadLine(); 
Output

output


Similar Articles