Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Jagged array in c#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 87
    Comment on it

    Jagged array is an array of array it means jagged array is a collection of homogeneous arrays. An arrays inside the jagged array are of different length. As the jagged array contains the arrays therefore its collection of homogeneous reference type elements.

     

    Syntax:
    int [][]ar;


    We can Declaration and initialization of jagged array in two way :

    1. First Method


    int [][]ar=new int[5][];
    ar[0] = new int[3];
    ar[1] = new int[5];
    ar[2] = new int[2];
    ar[3] = new int[4];
    ar[4] = new int[6];

    ar[0] = new int[] { 9, 5, 90 };
    ar[1] = new int[] { 10, 20, 22, 40, 46 };
    ar[2] = new int[] { 11, 56 };
    ar[4] = new int[] { 1, 60, 2, 47, };
    ar[6] = new int[] { 4, 5, 2, 4, 67, 34 };

     

    2. Second Method


    int[][] ar= new int[][]
    {
    new int[] { 9, 5, 90 },
    new int[] { 10, 20, 22, 40, 46 },
    new int[] { 11, 56 },
    new int[] { 1, 60, 2, 47, }
    new int[] { 4, 5, 2, 4, 67, 34 }
    };

     

    Below example illustrate the how to use a jagged array

    using System;
    namespace ArraySampleApplication
    {
       class JaggedArrays
       {
          static void Main(string[] args)
          {
             int[][] arr = new int[][]{
                               new int[]{10,20,30,40},
                               new int[]{11,22,33,44},
                               new int[]{20,40,50,60},
                              };
             int i, j;
             for (i = 0; i < 3; i++)
             {
                for (j = 0; j < 4; j++)
                {
                   Console.WriteLine("arr[{0}][{1}] = {2}", i, j, arr[i][j]);
                }
             }
             Console.ReadKey();
          }
       }
    }
    

     

    OUTPUT

    arr[0][0]=10
    arr[0][1]=20
    arr[0][2]=30
    arr[0][3]=40
    
    arr[1][0]=11
    arr[1][1]=22
    arr[1][2]=33
    arr[1][3]=44
    
    arr[2][0]=20
    arr[2][1]=40
    arr[2][2]=50
    arr[2][3]=60
    
    
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: