Thursday, 25 July 2013

Jagged Array in C Sharp

Jagged Array

Jagged array is simply an array of arrays. As we define 2-d array in which each column for each rows are same. But in case of jagged array we can define different column for each rows.

For Example:-

  int[][] jarray =new int[3][];

In this example I declared 2-d array in which rows are 3 but columns are not fixed. We can define column at the runtime for each rows using the following code:-

jarray[0] = new int[3] { 4, 5, 6 };
jarray[1] = new int[2] { 7, 8 };
jarray[2] = new int[4] { 9, 10, 34, 12 };


Traversing the jagged array using foreach loop:-

foreach (int[] data in jarray)
        {

            foreach (int p in data)
            {

                Response.Write(p + "<br/>");
           
            }
        }

Traversing the jagged array using For loop:-

for (int x = 0; x < jarray.Length; x++)
        {

            for (int y = 0; y < jarray[x].Length; y++)
            {

                Response.Write(jarray[x][y] + "<br/>");
           
            }
       
        }


No comments:

Post a Comment