Monday, August 16, 2010

Jagged array in C#

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. A jagged array is sometimes called an "array of arrays".

Declaration:       int[][] array;


Initialization:      array=new int[3][];
                        array[0]=new int[2];
                        array[1]=new int[5];
                        array[2]=new int[3];

 
Eg:
 
using System;

class jaggedarray
{
int[][] ja;


public void Accept()
{
Console.WriteLine("Enter the size of jagged array :");
int jsize = Convert.ToInt32(Console.ReadLine());
ja = new int[jsize][];
for (int i = 0; i < jsize; i++)
{
Console.WriteLine("Enter size of Single dimension array ");
int ssize = Convert.ToInt32(Console.ReadLine());
ja[i] = new int[ssize];
Console.WriteLine("Enter {0} elements ", ssize);
for (int j = 0; j < ssize; j++)
{
ja[i][j] = Convert.ToInt32(Console.ReadLine());
}
}
}


public void Display()
{
Console.WriteLine("Jagged Array Is :");
foreach (int[] a in ja)
{
foreach (int n in a)
{
Console.Write(n + "\t");
}
Console.WriteLine();
}
}
}


class Mainclass
{
public static void Main()
{
jaggedarray obj = new jaggedarray();
obj.Accept();
obj.Display();
}
}

No comments: