seegongsik
Saved words
Programming

A Row of Boxes: Arrays

One value, one box. That was a variable. But what if you need to hold a hundred things, like a class roll? You can't name a hundred boxes. So you line them up in one container. That's an array.

0
1
2
3
4
5

Drop values in, one by one. The row fills up.

Every slot gets a position number.
Computers count positions from 0, so the first slot is number 0.
The position number really means how many steps you are from the front, so the first slot, zero steps away, lands on 0.

 
7
0
3
1
9
2
1
3
5
4
8
5

Pick a number and that slot lights up. "What's sitting in slot 2?"

01

How many are there

The row can grow or shrink, and you can always count how many slots it holds.
And knowing the length also gives you the last slot's number, which is one less than the length because the count starts at 0.

3
7
0
3
1
9
2

Add some, remove some. The count follows along.

02

Walking one slot at a time

The loop from lesson 7 really shines here.
From the first slot to the last, you walk one step at a time and look at every one.
This walk works because the step count is the position number itself, so the 0, 1, 2 the loop counts points straight at the next slot to visit.

7
0
3
1
9
2
1
3
5
4
8
5

Hit play. It hops slot by slot, scanning the whole row.

03

A row has order

Swap two slots and they trade places. Squeeze one into the middle and everything behind shifts over.
Because it's a row, the order means something.
So squeezing into the middle takes effort because everything behind must shift, while adding at the very end is far easier since nothing has to move.

Tap two slots to swap
0
1
2
3
4

Tap two slots to swap them. Insert in the middle and the rest slide back.

Inside the computer these slots really do sit side by side, like lockers in a row.
A container that labels each slot by name is coming up next.
Because they sit packed in order like this, the computer reaches any slot in one leap, skipping ahead by the position number instead of searching from the front.

In one lineAn array lines things up in a row so you can grab any one by its position number.
Programming
Was this helpful? Support seegongsik