Why array indexing starts from ZERO???

Varshil Shah
2 min readAug 2, 2023

--

In computer science, arrays are a data structure that stores a collection of elements of the same type. The elements of an array are indexed starting from 0, which means that the first element is at index 0, the second element is at index 1, and so on. There are a few reasons why array indexing starts from 0, including historical reasons, performance reasons, and mathematical reasons.

Whenever you declare an array, most of the time you want to iterate through complete array to access it’s all elements, right? So how compiler knows at which memory address the data is available?

For zero based indexing

In the above picture, there is an array A which has 5 elements present in it and it starts with the location of memory address 200. For this example, let’s consider that integers take 2 bytes of memory.

There are 2 ways that compiler computes to get the location of memory address in an array, the first way is Row Major & the second is Column Major. C/C++ compiler uses Row Major to compute memory address. All though, both the ways are efficient.

In the above picture, we are using ZERO based indexing. So, to access any element of the array, our compiler uses the given formula.

Address(A[i]) = L0 + i * w

Here, L0 stands for Base Address, i stands for index and w for size of data type. In order to get the data, compiler performs 2 operations, addition and multiplication.

For one based indexing

Here, we are using ONE based indexing and all the other things are same. So, to access any element of the array, our compiler uses the given formula.

Address(A[i]) = L0 + (i - 1) * w

Here, L0 stands for Base Address, i stands for index and w for size of data type. In order to get the data, compiler performs 3 operations, addition subtraction and multiplication.

As of now we have seen, in zero based indexing, only 2 operations are required to get the value at a given index and in one based indexing the same is done by using 3 operations.

Conclusion

As ONE based indexing performs has to perform 3 operations, due to this the performance decreases as compared to ZERO based indexing. Therefore, ZERO based indexing is used in arrays.

--

--

Varshil Shah

Hey! I'm Varshil Shah, Currently pursing B.tech in Computer Engineering