🌱 Beginner's Guide lesson 7 of 12

Arrays

A variable holds one value. But what if you want to keep track of lots of values: all the scores in a game, every name in your class, the items in your backpack? You could make name1, name2, name3... but there's a much better way: an array, a single variable that holds a whole list of values, in order.

Making an array

Write the values inside square brackets [ ], separated by commas:

[ try-it.sts ]
bongSlanhOun "fruit";
akthe fruits = ["mango", "durian", "rambutan"];
akthe scores = [12, 7, 30];
jongyeytha fruits;
jongyeytha scores;
[ what it prints ]
[mango, durian, rambutan]
[12, 7, 30]

An array can hold values of any type, but all the values in one array must have the same type. The type of an array is written with square brackets around the type of its items:

type means
[Ahsor] an array of strings
[LekKut] an array of whole numbers
[Boolean] an array of yes/no values

So fruits above is an [Ahsor], and scores is a [Lek].

Getting one item out

Each item has a position number, called its index. Here's the twist: counting starts at 0, not 1. The first item is at index 0, the second at index 1, and so on.

[ try-it.sts ]
bongSlanhOun "index";
akthe fruits = ["mango", "durian", "rambutan"];
jongyeytha fruits[0];
jongyeytha fruits[1];
jongyeytha fruits[2];
[ what it prints ]
mango
durian
rambutan

Why zero? Think of the index as "how many steps from the start". The first item is zero steps in. It's odd for a day or two, then it feels natural, promise.

You can also change an item by putting it on the left of =:

[ try-it.sts ]
bongSlanhOun "change";
akthe pets = ["cat", "dog", "fish"];
pets[2] = "turtle";
jongyeytha pets;
[ what it prints ]
[cat, dog, turtle]

How long is it? .len()

Every array can tell you how many items it has. Put .len() after it (short for "length"):

[ try-it.sts ]
bongSlanhOun "len";
akthe planets = ["Mercury", "Venus", "Earth", "Mars"];
jongyeytha planets.len();
jongyeytha "The last planet here is " + planets[planets.len() - 1];
[ what it prints ]
4
The last planet here is Mars

There are 4 items, so the indexes go from 0 to 3. The last index is always one less than the length.

Adding items: .push(x)

.push(x) adds a new item onto the end, so the array grows:

[ try-it.sts ]
bongSlanhOun "push";
akthe backpack = ["water"];
backpack.push("snacks");
backpack.push("sunscreen");
jongyeytha backpack;
jongyeytha backpack.len() + " things packed";
[ what it prints ]
[water, snacks, sunscreen]
3 things packed

Things like .len() and .push(x), that belong to a value and are called with a dot, are called methods. They're functions that come built into the array.

To start with an empty array, steav2 needs to be told what type of items it will hold, since there's nothing inside to look at yet:

[ try-it.sts ]
bongSlanhOun "empty";
akthe squares: [LekKut] = [];
somhab (akthe i: LekKut = 1; i <= 5; i += 1) {
    squares.push(i * i);
}
jongyeytha squares;
[ what it prints ]
[1, 4, 9, 16, 25]

Looping over an array

Arrays and somhab loops are best friends. Count from 0 up to (but not including) the length, and use the counter as the index:

[ try-it.sts ]
bongSlanhOun "loop";
akthe friends = ["Bopha", "Rithy", "Chenda"];
somhab (akthe i: LekKut = 0; i < friends.len(); i += 1) {
    jongyeytha "Hi, " + friends[i] + "!";
}
[ what it prints ]
Hi, Bopha!
Hi, Rithy!
Hi, Chenda!

Remember how we always made our counter a LekKut? Here's why. Indexes are always whole numbers (there's no item number 1.5!), so array indexes and .len() are LekKut. If the counter were a LekThom, steav2 would complain that the numbers don't mix.

Here's a loop that adds up a list of numbers and finds the average:

[ try-it.sts ]
bongSlanhOun "average";
akthe marks = [70, 85, 90, 64];
akthe total = 0;
somhab (akthe i: LekKut = 0; i < marks.len(); i += 1) {
    total += marks[i];
}
jongyeytha "Total: " + total;
jongyeytha "Average: " + total / LekThom(marks.len());
[ what it prints ]
Total: 309
Average: 77.25

marks.len() is a LekKut, so we convert it with LekThom(...) before dividing a Lek by it.

Falling off the end

What happens if you ask for an index that doesn't exist?

[ x_x broken on purpose ]
bongSlanhOun "too far";
akthe colors = ["red", "green", "blue"];
jongyeytha colors[0];
jongyeytha colors[3];
jongyeytha "we never get here";
[ what it prints ]
[line 4] runtime error: index 3 is out of bounds, the array has 3 items

This is a different kind of error from the ones we've seen so far. Those were found before the program ran. This one is a runtime error: the program started, printed red, and then crashed when it reached line 4. steav2 can't always know in advance which index you'll ask for, so it checks while the program runs, and stops it rather than giving you nonsense.

Your turn

  1. Make an array of your five favourite songs (or snacks, or games) and print each one with its position, like 1. Mango sticky rice. Hint: the position is i + 1.
  2. Find the biggest number in [4, 18, 7, 21, 3]. Hint: start with akthe best = numbers[0]; and loop, replacing best whenever you find something bigger.
  3. Build an array of the first 10 even numbers using .push, then print it.

Solution for exercise 2:

[ try-it.sts ]
bongSlanhOun "biggest";
akthe numbers = [4, 18, 7, 21, 3];
akthe best = numbers[0];
somhab (akthe i: LekKut = 1; i < numbers.len(); i += 1) {
    ber (numbers[i] > best) {
        best = numbers[i];
    }
}
jongyeytha "The biggest is " + best;
[ what it prints ]
The biggest is 21
  • steav2♡ help
  • Y2K✓ ready
  • wasminside
  • .stsvalid

best viewed at 1024x768 ☆ made with ♡ ☆ the reference is steav2's own docs