What is an array in programming
One value, one box: that was a variable. But if you need to hold a hundred values, like a class register, you can't give a hundred boxes a hundred names. So the values are lined up in a single row, and that's an array.
Each time you press "add one," an empty cell fills, until the row is full.
Every cell gets a position number.
Computers count positions from 0, so the first cell is number 0.
A position number really means how many steps you are from the front. The first cell isn't even one step away, so it's number 0.
Pick a number and only that position lights up. "What's in position 2?"
How many are there?
However long or short the row gets, you can always count how many cells it has.
And once you know the length, you know the last position number too: since counting starts at 0, the last number is one less than the length.
Add and remove values, and the length follows.
Walking one cell at a time
The loops from Lesson 7 shine here.
You can walk from the first cell to the last, one at a time, and look at every one.
That works because the step count is the position number, so the 0, 1, 2 a loop counts point straight to the next cell to look at.
Press play and it moves one cell at a time, scanning the row.
It's a row, so order matters
Swap two cells and their positions change; slip one into the middle and everything after it shifts back one cell.
Because it's a single row, order carries meaning.
That's why inserting in the middle takes work, since everything behind has to move, while adding to the very end moves nothing and is much easier.
Pick two positions and they swap; insert in the middle and the rest shift back.
Inside a computer, too, these cells sit side by side like lockers.
Because they're packed tightly in order, the computer doesn't search from the start for any cell; it jumps ahead by the position number and lands on it in one go.
A container that labels each slot with a name instead of a number is coming up in a later lesson.