Iterate Through an Array with a For Loop challenge


I need help in understanding the logic behind the zero-based numbering and the length property = -1.

Zero-based arrays have their roots in C and even assembler. With C, pointer math basically works like this:

Each element of an array occupies a certain number of bytes. A 32 bit integer is (obviously) 4 bytes;
The address of an array is occupied by the first element of the array with subsequent elements in equal-sized contiguous blocks after that.
To illustrate, assume int a[4] is at 0xFF00, the addresses are:

a[0] -> 0xFF00;
a[1] -> 0xFF04;
a[2] -> 0xFF08;
a[3] -> 0xFF0C.
So, with zero based indices, the addres math is simple:

Address of element = Address of array + index * sizeof(type)

In fact the expressions in C are all equivalent:

a[2];
2[a]; and
*(a+2).
With one-based arrays, the math is (ever so) slightly more complicated.

So the reasons are largely historical.

Courtesy: < https://softwareengineering.stackexchange.com/questions/110804/why-are-zero-based-arrays-the-norm >

An array of n elements has length=n. Since 0 is the first index of the array this means the last index of the array is n-1 because there are n indexes from 0 through n-1 - so the last index in terms of length is length - 1

For why zero-based numbering is common in programming see
https://en.wikipedia.org/wiki/Zero-based_numbering

For why zero-based numbering is right for programming see
https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

I like to think of it like a measuring tape or ruler: 1 isn’t the far edge of the ruler, 0 is. You can’t use ‘1’ until you pass it. So, based on that, item 2 in the below ascii art is technically in the ‘1’ block.

  item1    item2    item 3    
|--------|--------|---------|
0        1        2         3

Remembering that you can’t use it until you pass it means that you can never use arr.length because that number hasn’t been passed. The last item is still in the previous block… so you need to -1 to get there. There are 3 items in the ascii art, but item 3 is still in block 2.

Same analogy works for birthdays. A newborn baby isn’t 1 (unless you’re doing that crazy asian thing where they count from conception :stuck_out_tongue_closed_eyes:), it’s 0 until it’s first birthday.

All of our standard measuring practices are actually zero-based. Most people aren’t forced to realize that though. :wink: