Monday, July 22, 2013

Jagged Arrays

In C Sharp: Jagged Arrays are described as it is collection of arrays of different or same number of elements in it but of similar type only.

Syntax of the Jagged Array
---------------------------

int[ ][ ] <<Jagged Array variable Name>  =  new int [ 2 ][ ];

int[ ][ ] jagged_array  =  new int [ 2 ][ ];

In above syntax, jagged_array is variable of Array data type, where it is having 2 Arrays in it.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo_20
{
    class Program
    {
        static void Main(string[] args)
        {

            //Declare two elements of the Array

            int[][] array = new int[2][];

            //filling the elements
            array[0] = new int[5] { 1, 3, 5, 7, 9 };
            array[1] = new int[4] { 2, 4, 6, 8 };

            //Display the array elements

            for (int i = 0; i < array.Length; i++)
            {
                Console.Write("Element of Array [{0}]: ", i);
                for (int j = 0; j < array[i].Length; j++)
                {
                    Console.Write("{0}{1}", array[i][j], j == (array[i].Length - 1) ? "" : "",i,j);
                }
                Console.WriteLine();
            }    

        }
    }
}

No comments:

Post a Comment