Why array index starts from zero ?
Prerequisite : Pointers in C/C++
THERE CAN BE MANY REASONS, BUT HERE ARE TWO REASONS:
Reason 1 :
Consider int arr. The answer lies in the fact how the compiler interprets arr[i] ( 0<=i<100).
arr[i] is interpreted as *(arr + i). Now, arr is the address of the array or address of 0th index element of the array. So, address of next element in the array is arr + 1 (because elements in the array are stored in consecutive memory locations), further address of next location is arr + 2 and so on. Going with the above arguments, arr + i mean the address at i distance away from the starting element of the array. Therefore, going by this definition, i will be zero for the starting element of the array because the starting element is at 0 distance away from the starting element of the array. To fit this definition of arr[i], indexing of array starts from 0.
The conclusion is, we need random access in the array. To provide random access, compilers use pointer arithmetic to reach i-th element.
Reason 2 :
Modern languages, especially C++ use row-major ordering for storing two-dimensional arrays.
Let us assume a 2D array and write a row-major formula with two different approaches:
- array indices starting from 1
- array indices starting from 0
let the 2D array be arr[m][n] of type int
let &arr be “address”
case 1 ( array indices start from 1 ) :
&( arr[i][j] ) = address + [ ( i-1 )*n + ( j-1 ) ]*( sizeof(int) ) ] so here we are performing 6 operations
case 2 ( array indices start from 0 ) :
&( arr[i][j] ) = address + [ ( i )*n + ( j ) ]*( sizeof(int) ) ] and here we are performing only 4 operations
So we see here that we are performing 2 less operations when we store 2D arrays and obtaining an element’s address. This looks like it doesn’t make sense but it does! While handling with huge size data this may improved performance and speed. case 1 may look user-friendly but case 2 is more efficient. That’s why most languages like C++, PYTHON, JAVA use arrays starting with index 0 and rarely languages like Lua arrays starting with index 1.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.