Why array indexing starts with 0 in C, C++, Java and most of other programming languages is one of the common confusion among programmers.
In this article I will tell you the reason behind it.
Why Array Indexing Starts with 0 in C?
Lets try to understand this by taking one example in C. We can declare an array of size 5 in following way.
Here a itself is a pointer which contains the memory location of first element of the array.
Now for accessing the first element we will write a which is internally decoded by compiler as *(a + 0).
In the same way the second element can be accessed by a or *(a + 1). As a contains the address of first element so for accessing second element we have to add 1 to it. Thats why here we have written *(a +1).
In array the index describes the offset from the first element, i.e. the distance from the first element.
Now lets assume that array indexing starts with 1 instead of 0. In this case for accessing the first element we have to write a which is internally decoded as *(a + 1 – 1).
Observe here that we have to perform one extra operation i.e. subtraction by 1. This extra operation will greatly decrease the performance when the program is big.
Thats why to avoid this extra operation and improve the performance, array indexing starts with 0 in C, C++, Java, etc.
Comment below if you have any queries regarding above article. Do share it if you found this information valuable.