Saturday, August 10, 2013

Array index start with zero Why?

Array is collection of fixed size homogeneous type of elements.In this post i will explain "Why Array index start with zero on-wards".Generally we cannot think about this question because no one ask this type of questions in interview or anywhere.But in present interview panels asking this question frequently.So we should knowing this one is important for improving knowledge on language(C,C++,JAVA,etc).Before knowing about our topic first we know " How does array store in memory?".Array store in memory based address value.And we are printing element then it use offset value of physical address for getting values.

                   When we are creating the array variable we declare and initialize size of the array. Then we take values from console or directly we can assign.
         Ex:
              int studentNos[]={10,20,60,30,40,80,90,100,50};
                 
                   The array variable is store in memory.The value of array variable is address of zero th index of array.See below diagram

From above diagram we can know how array is storing in memory.After creating array, array variable store only address of zeroth index.Based on this value it calculate addresses of remaining indexes of array.For example, we calculate zeroth index of array based on offset value.Now we discuss "Why array index start with zero?".

 address of zeroth index of array=array variable address + datatype in bytes *  index of array;
                                                 =1000+2*0
                                                 =1000+0
                                                 =1000
Now we got address of zero index then we get value of zeroth index by using &.
 value of zero index of array =&(1000)

                                           =10

Then remaining also calculated like above.


No comments:

Post a Comment