Sunday, January 20, 2013

Difference between Jagged Array and Multi Dimension Array in C#?


Jagged Array

A jagged array is an array whose element is arrays and the element of jagged array could be of different size and dimension.

Multi Dimension Array

A multi dimension array is an array whose element will be of same size.


Jagged Array Example


       
     
         
   

3-Dimension Array Example


     
     
     


Example

    class JaggedArray
    {
        static void Main()
        {
            // Declare jagged array of size 4.
            int[][] objJaggedArray = new int[4][];

            // Initialization jagged array.
            objJaggedArray[0] = new int[4];
            objJaggedArray[1] = new int[3];
            objJaggedArray[2] = new int[5];
            objJaggedArray[3] = new int[2];


            objJaggedArray[0] = new int[] { 9, 8, 7, 6 };
            objJaggedArray[1] = new int[] { 9, 8, 7 };
            objJaggedArray[2] = new int[] { 9, 8, 7, 6, 5 };
            objJaggedArray[3] = new int[] { 9, 8 };

            Console.WriteLine("Jagged Array Items...");

           // Display the jagged array elements:              
            for (int i = 0; i < objJaggedArray.Length; i++)
            {
                Console.WriteLine();
                for (int j = 0; j < objJaggedArray[i].Length; j++)
                {
                    Console.Write(objJaggedArray[i][j]+ " ");
                }
            }

            Console.WriteLine();

            int[,] myArray = new int[3, 3];
            myArray[0, 0] = 1;
            myArray[0, 1] = 2;
            myArray[0, 2] = 3;
            myArray[1, 0] = 4;
            myArray[1, 1] = 5;
            myArray[1, 2] = 6;
            myArray[2, 0] = 7;
            myArray[2, 1] = 8;
            myArray[2, 2] = 9;

            Console.WriteLine("3D Array Items...");

            // Display the 2D array elements:             
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(myArray[i, j] + " ");
                }
                Console.WriteLine();
            }            


            Console.ReadLine(); 

        }
    }
            

Output

Jagged Array Items...
9 8 7 6
9 8 7
9 8 7 6 5
9 8

3D Array Items...
1 2 3
4 5 6
7 8 9

No comments:

Post a Comment