Why array index starts from zero in C/C++ ?


An array arr[i] is interpreted as *(arr+i). Here, arr denotes the address of the first array element or the 0 index element. So *(arr+i) means the element at i distance from the first element of the array. So array index starts from 0 as initially i is 0 which means the first element of the array.

A program that demonstrates this in C++ is as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int arr[] = {5,8,9,3,5};
   int i;
   for(i = 0; i<5; i++)
   cout<< arr[i] <<" ";
   cout<<"\n";
   for(i = 0; i<5; i++)
   cout<< *(arr + i) <<" ";
   return 0;
}

Output

The output of the above program is as follows.

5 8 9 3 5
5 8 9 3 5

Now let us understand the above program.

An array arr[] contains 5 elements. These elements are displayed using a for loop with array representations arr[i] and *(arr + i). The results obtained are identical in both cases. The code snippet that shows this is as follows.

int arr[] = {5,8,9,3,5};
int i;
for(i = 0; i<5; i++)
cout<< arr[i] <<" ";
cout<<"\n";
for(i = 0; i<5; i++)
cout<< *(arr + i) <<" ";

Updated on: 26-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements