I'm curious about why array indexing starts at 0 in programming. For example, when I create an integer array, the first element is accessed with index 0. Is there a fundamental reason behind this? Also, does the indexing behave differently when we deal with arrays of strings?
1 Answer
The 0-based indexing comes from how arrays are handled in memory. Essentially, the array's elements are stored sequentially, and the index represents how many elements away from the start of the array you want to access the data. So, to access an element at a specific index, you calculate its address by adding the index multiplied by the size of each element to the starting memory address. This pattern is consistent no matter what type of data the array holds, whether integers or strings!

Just to add a little nugget: while many languages stick to 0-based indexing, some, like Lua, kick off from 1 instead. It's interesting to see how different languages handle this!