C++, C#, C, D, Java,... are zero based.
Matlab is the only language I know that begin at 1.
Because there are 10 integers 0..9
I guess because arrays use pointer arithmetic to refer to some value. Basically arrays have contiguous memory and if you want to refer to 5th element (a[4]) then a + 4 * size of int is performed
Say if you start with 1 then to refer to 5th element you will have to do something like a + (5-1) * size of int
I guess it has mostly historical reasons, new languages just try to use the existing convention which programmers are familiar with.
Older languages from which this rule originated were close to the metal, and an index is really the distance from the starting element, hence 0
makes sense for the first element.
Arrays are zero based in c and c++ as the represent the offset from the beginning of the list of the item.
These two lines have identical result in c.
anArray[3] = 4;
*(anArray +3) = 4;
The first is the standard indexer the second takes the pointer adds three to id and then dereffrences it. Which is the same as the indexer.
Well, consider Dijkstra's famous article, Why numbering should start at zero. He argues that numbering should start at 0 because it means that the valid indexes into an array can be described as 0 <= i < N
. This is clearly more appealing than 1 <= i < N + 1
, on an aesthetic level.
(One could ask, "why not say 0 < i <= N
", but he argues against that, too, again for aesthetic reasons.)
Probably "C" got it because it is more efficient. To calculate address of item in 0-based array it is enough to multiple Index by ItemSize, for 1-based array you have to calculate (Index-1)*ItemSize. "C" and then "C++" where most popular languages, so new languages have to follow same rules, it helps to avoid mistakes for those who use C/C++. But this question seems to be offtopic and i guess it will be closed by moderator.
P.S. In Delphi/Pascal strings are 1-based, but for arrays you have to provide range and so you can use what you like.