How to access elements from jagged array in C#?

CsharpProgrammingServer Side Programming

A Jagged array is an array of arrays. To access an element from it, just mention the index for that particular array.

Here, we have a jagged array with 5 array of integers −

int[][] a = new int[][]{new int[]{0,0},new int[]{1,2}, new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };

Let’s say you need to access an element from the 3rd array of integers, for that −

a[2][1]

Above, we accessed the first element of the 3rd array in a jagged array.

Let us see the complete code −

Example

using System;

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

         int[][] a = new int[][]{new int[]{0,0},new int[]{1,2}, new int[]{2,4},new int[]{ 3, 6 }, new          int[]{ 4, 8 } };
         int i, j;

         for (i = 0; i < 5; i++) {
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
            }
         }

         // accessing element from a jagged array
         Console.WriteLine(a[2][1]);

         Console.ReadKey();
      }
   }
}
raja
Published on 13-Aug-2018 12:38:26
Advertisements