Why is array indexing done with 0 and not with 1 in programming languages like Java ? I am totally new to java any explanation is welcomed.
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.
Array index always starts from 0 Programming languages are desinged in a such a way that the array name is always points to the first element of an array.
Java uses zero-based indexing because c uses zero-based indexing. C uses zero-based indexing because an array index is nothing more than a memory offset, so the first element of an array is at the memory it's already pointing to, *(array+0)
.
See also Wikipedia's array indexing in different languages?
To expand upon @Kevin's answer, I take this quote from an answer on Programmers.SE:
The index in an array is not really an index. It is simply an offset that is the distance from the start of the array. The first element is at the start of the array so there is no distance. Therefore the offset is 0.
Further, if you want to learn more about how different languages do their array indexing, then look at this exhaustive list on Wikipedia.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With