Why Index of An Array Starts With 0... ?

 In most languages like Java, C++, C  index of the array starts with zeros, while indexing of arrays in some languages like Cobol, Julia, Lua, etc. starts with 1. Let's try to understand the 0-based array indexing in this post.




TRACK  1 :

When we try to access an element from an array then internally it uses the following formula- 

=  Base Address + Index * Size of DataType 

EXAMPLE: suppose array index start from one and base address of the array is 100

int[ ] arr={5,10,15,20}

respective address are : 100,104,108,112

so when we try to access the first element then it acts like= 100+1*4=104

but 104 is the address of the second element, not the first one, Thus we cannot access the first element in the array if an index of the array starts with one.


TRACK  2 :

Let's try to understand the same problem in another way-

A[i] in an array is implemented as (A+i) 

for example, if you have an array of integers and each integer takes 4 bytes. Assume the memory address starts with 100 then memory locations for each consecutive element will be 100,104,108,112,116...but if we start the index of an array with 1then A[i] will be implemented as (A+i-1) which will be time-consuming during compilation and the performance of the program will also be affected. So, it is better to start the index of the array from zero.





Keep coding : Keep sharing

 

Popular posts from this blog

"The Blogosphere Unleashed: ChatGPT's Insights into the Future of Blogging"

Naval Ravikant : How to Get Rich ( Without Getting Lucky)