As the Array indexing always starts with 0, is there a way to change it to begin with 1 instead of 0? [duplicate]
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.
Solution 1:
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?
Solution 2:
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.
Solution 3:
A quote by Dijkstra, from Why numbering should start at zero (1982):
When dealing with a sequence of length N, the elements of which we wish to distinguish by subscript, the next vexing question is what subscript value to assign to its starting element. Adhering to convention a) yields, when starting with subscript 1, the subscript range 1 ≤ i < N+1; starting with 0, however, gives the nicer range 0 ≤ i < N. So let us let our ordinals start at zero: an element's ordinal (subscript) equals the number of elements preceding it in the sequence. And the moral of the story is that we had better regard —after all those centuries!— zero as a most natural number.
A discussion about this article can be found in Lambda the Ultimate - Why numbering should start at 0.