Thursday, July 9, 2009

Why in programming language like C, Array starts with index 0 and not with index 1 ?

In array if we want to store 10 elements then we have indexes as 0,1,2,3 upto 9. My question is that why the array starts with index 0 and not with 1. If there are 10 elements to store then indexes must be 1, 2, 3, upto 10. But it is 0,1,2,3 upto 9.

Why in programming language like C, Array starts with index 0 and not with index 1 ?
As a design matter, the modulo operator is used (modulo of size), this gives zero as the starting point and (size -1) as the highest value. The other answers pointing out that the 0th element is also the array itself are also relevant, though it is an effect rather than the cause.
Reply:Generally in computers everyting starts with 0. Addresses strats with 0. Numbers starts with 0. We can say when the counting of number for others ends with 0, the counting of computers starts.
Reply:Hmmm.Good question. Looks like you have to ask the one who invented the programming language.





dates back to C (or maybe even later). say p is a array reference. In C, p is really a pointer to the first element. p is really a short cut for *(p+i). So to access the first element we write *(p+0) or more concisely a[0].





because the name of an array is actually a pointer to the first element of this array in memory :array[0] is equivalent to *arrayarray[1] is equivalent to *(array + 1)...array[i] is equivalent to *(array + i)
Reply:If you consider the index as simply an offset from the start point of your array in storage then 0 is valid, i.e no offset...
Reply:An array name is just a pointer to the location of the first element in that array. The number in the square brackets denotes the positive offset from that first element. Therefore if the offset is 0 you are looking at the first element. Also (in C)


array[23]==array+23==array[10]+13
Reply:Good news for you, you if you have plenty of memory and we do these days, you can define your Arrays to have 11 elements and then skip the 0 index and begin at 1. You have my permission to write this code. I have done this many times with other programming languages, I want item 1 to be element one, do define the array one larger. Be well, ps, there is no charge for this bit of wisdom today. The code will execute fine, if you write it correctly.
Reply:An array in C++ is static (has fixed value) and is primitive (predefined in the compiler) therefore it is predefined to start with zero to have uniformity... but there are others where the initial value of array can be altered (even be put in negative!).


No comments:

Post a Comment