How to access elements from an array in C#?

CsharpProgrammingServer Side Programming

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();
      }
   }
}
raja
Published on 13-Aug-2018 16:24:13
Advertisements