While working with arrays in any language, I have always wondered why does the base address or index number of an array start with zero.
int x[5]={21,34,55,314,45};
now if I want to access any the first value of an array I would have to use x[0], but why 0 is there any logic behind this?
In C, the name of an array is essentially a pointer, a reference to a memory location, and so the expression array[n] refers to a memory location n-elements away from the starting element. This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array refers (0 elements away), so it should be denoted as array[0]. Most programming languages have been designed this way, so indexing from 0 is pretty much inherent to the language as most of the languages (not all) follow C standards. You can refer this link for more details.
In general, the logic of working with zero-indexed arrays is considered to be simpler, once you think of the indices as offsets from the origin rather than as "places in a list": you start at the start of the list, and the first item is where you are when you start, ie, when you've gone zero steps.
In a sense, though, it's fundamentally arbitrary and probably convention is the best answer. If we consider that most modern languages were designed by people who learned C very early on in their careers, or more recently who based their designs on those C-inspired languages, the choice of zero-indexed arrays would have been a pretty big change which would have required a lot of justification, which nobody seems to have found, or possibly even looked for. However, if there were ever a real reason to use 1-indexed arrays, there wouldn't be any real reason not to use them.
Of course, as we get into more modern language design the idea of caring about the index of an array element is receding from relevance. For example, python programmers loop over an index like this:
for element in lst:
do_stuff_to(element)
and therefore don't have a reason to care about the index. Ruby has even hipper ways of dealing with this problem, which I won't illustrate here but which you should look into.
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