Do you know why the C++ array is indexed from zero and not one?
Suppose we have an Array (A) where the size of data type W is 2 bytes(or 4 bytes for int
, depends on the compiler), and the
Logical Address(A[i]) = Base Address() + ( i - 1 ) * W
In this formula, we have to perform three arithmetic operations +
, -
, and *
, but when we take the zero as the starting index, the formula becomes:
Logical Address(A[i]) = Base Address() + ( i ) * W
This arithmetic operation only has +
and *
,
so if the size of an array is n, then the starting index formula will execute slower due to the one extra operation overhead. This will, therefore, affect the time taken by the program for larger values of n.
And hence, we use ZERO as the starting index rather than ONE.