Array indexing starting from zero
What you'll learn: Why C counts starting from zero and how to pinpoint specific data slots within an array.
The "Zero-Based" Rule
In everyday life, if you have a row of five lockers, you probably point to the first one and say, "That’s locker number one." In C programming, however, the count always starts at 0.
Think of an array as a hotel hallway. Instead of counting the number of doors you’ve passed, C thinks about the distance (or offset) from the very beginning of the hallway. If you are standing at the very first door, you have moved zero steps from the start. Therefore, the first room is index 0.
How it looks in code
When you want to access a specific item in an array, you place the index number inside square brackets [].
#include <stdio.h>
int main() {
// Create an array of 3 integers
int luckyNumbers[3] = {7, 13, 21};
// The first element is at index 0
printf("First number: %d\n", luckyNumbers[0]);
// The second element is at index 1
printf("Second number: %d\n", luckyNumbers[1]);
// The third element is at index 2
printf("Third number: %d\n", luckyNumbers[2]);
return 0;
}
The "N-1" Mental Trick
Because we start at zero, the "address" of the last item is always one less than the total size of the array. If you have an array of 10 items, the first is [0] and the very last is [9].
If you try to access luckyNumbers[3] in the example above, you are asking C for the fourth item in a three-item list. This is a common mistake called an "off-by-one" error. C won't always stop you from doing this, but it will lead to your program grabbing random junk data from your computer's memory or crashing entirely.
Why do we do this?
It might feel unnatural at first, but zero-based indexing makes the computer's math much faster. The index tells the computer exactly how many "slots" to skip over from the start to find your data. To get to the first item, you skip 0 slots. To get to the second item, you skip 1 slot.
Key takeaway
In C, the first element of an array is always at index 0, and the last element is at index size - 1.