How to access elements from an array in C#?


First, define and initalize an array −

int[] p = new int[3] {99, 92, 95};

Now, display the array elements −

for (j = 0; j < 3; j++ ) {
   Console.WriteLine("Price of Product[{0}] = {1}", j, p[j]);
}

To acess any element, just include the index of the element you want like this −

p[2];

The above is to acess the 3rd element.

Now let us see the complete code −

Example

using System;

namespace Program {
   class Demo {
      static void Main(string[] args) {
         int[] p = new int[3] {99, 92, 95};
         int j;

         for (j = 0; j < 3; j++ ) {
            Console.WriteLine("Price of Product[{0}] = {1}", j, p[j]);
         }

         // access
         int e = p[2];
         Console.WriteLine("Product 3rd price: "+e);

         Console.ReadKey();
      }
   }
}

Updated on: 21-Jun-2020

664 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements