Saturday, 18 March 2017

Why Array index always starts with 0 not with 1?

In programming languages like C,C++,Java there is concept of array which is used to hold more than one value of same datatype.The array contains index and its value.Its index always starts with 0.Have you ever got question like why it is 0 only not 1 or 2 or 3 and so on?
Array Structure in programming languages
 Let us find it out by understanding an example.
Suppose one array is declared as... 
int a[7];

Here a  is a pointer which contain location of first element.To access 1st element,we write a[0].This is assigned as *(a+0).For 2nd element,it is *(a+1).Because has address of 1st element so for 2nd element we will increment it by 1. 

Now assume that index starts with 1.Then to access 1st element,we write a[1]. So it will assigned *(a+1-1).As you can see here,the extra operation is performed that is subtraction.This will require more memory and time for compiler as compare to array index 0.Also the performance will degrade if program code is large.
So,to avoid the extra operations,array index always starts with 0.Please share this if it is valuable. :)