Are arrays zero indexed in C#?

CsharpServer Side ProgrammingProgramming

Yes, arrays zero indexed in C#. Let us see how −

  • If the array is empty, it has zero elements and has length 0.
  • If the array has one element in 0 indexes, then it has length 1.
  • If the array has two elements in 0 and 1 indexes, then it has length 2.
  • If the array has three elements in 0, 1 and 2 indexes, then it has length 3.

The following states that an array in C# begins with index 0 −

/* begin from index 0 */
for ( i = 0; i < 5; i++ ) {
   n[ i ] = i + 5;
}

Example

You can try to run the following to see how array indexing implements in C# −

Live Demo

using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[5];
         int i,j;
         /* begings from index 0 */
         for ( i = 0; i < 5; i++ ) {
            n[ i ] = i + 5;
         }
         for (j = 0; j < 5; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}

Output

Element[0] = 5
Element[1] = 6
Element[2] = 7
Element[3] = 8
Element[4] = 9
raja
Published on 24-Jul-2018 07:47:07
Advertisements