Arrays on the micro:bit: lists of numbers and words in MakeCode

Lesson 9 of 14 · micro:bit

A variable stores one value. When we need to remember several values – five temperature measurements, a list of answers, a melody of ten tones – we use an array (in MakeCode the Arrays palette). An array is a list of values under one name; every value has its own order number – the index.

Before you start: required prior knowledge – loops, variables and the Math palette.
How to learn: build every example in MakeCode and try it in the simulator (or on the device), and solve the tasks at the end on your own first; open the instructions and the solution only after that. The programs are given as blocks (description) and in JavaScript from MakeCode: in the editor click JavaScript, paste the code and go back to Blocks – you will get the same blocks.

Creating an array and indexes

An array is created with the block set list to array of … from the Arrays palette (it is under Advanced). In JavaScript we write the values in square brackets:

let grades = [5, 4, 5, 3]
basic.showNumber(grades.length)   // length of the array: 4
basic.showNumber(grades[0])       // first element: 5
basic.showNumber(grades[3])       // last element: 3

Important: indexes start from 0. An array of 4 elements has the indexes 0, 1, 2 and 3. An element with index 4 does not exist.

The array grades
Index0123
Value5453

An element is changed like an ordinary variable: grades[1] = 5 (the block set value at).

Adding and removing elements

BlockJavaScriptWhat it does
add value to endlist.push(x)adds x to the end of the array
get and remove last valuelist.pop()removes the last element and returns it
remove value atlist.removeAt(i)removes the element with index i
find index oflist.indexOf(x)index of the first occurrence of x (−1 if it is not there)
length of arraylist.lengthnumber of elements

Example: button A measures the temperature and adds it to the array; button B shows how many measurements have been saved.

let measurements: number[] = []      // empty array of numbers

input.onButtonPressed(Button.A, function () {
    measurements.push(input.temperature())    // new measurement at the end of the array
    basic.showIcon(IconNames.Yes)
})
input.onButtonPressed(Button.B, function () {
    basic.showNumber(measurements.length)     // number of saved measurements
})

Going through an array with a loop

The loop for element value of list (Loops palette) goes through all elements in order. This makes it easy to compute the sum, the average or the largest value:

let points = [12, 7, 15, 9]
let sum = 0
let largest = points[0]
for (let p of points) {
    sum += p                // we add up all elements
    if (p > largest) {
        largest = p         // we remember the largest so far
    }
}
basic.showNumber(sum)       // 43
basic.showNumber(largest)   // 15

If we also need the index, we use the loop for index from 0 to …. Be careful: the end value is length − 1.

let tones = [262, 294, 330, 349, 392]   // C, D, E, F, G
for (let i = 0; i <= tones.length - 1; i++) {
    led.plot(i, 2)                      // the i-th LED in the middle row
    music.playTone(tones[i], music.beat(BeatFraction.Half))
}

An array of words: the magic ball

An array can also contain words (strings). We choose a random element with a random index from 0 to length − 1:

let answers = ["YES", "NO", "MAYBE", "ASK AGAIN"]
input.onGesture(Gesture.Shake, function () {
    // random index from 0 to 3
    basic.showString(answers[randint(0, answers.length - 1)])
})

The micro:bit screen does not show letters with diacritics (such as č, š or ž), so use only the letters of the English alphabet in texts.

Practice tasks

For every task there is an example, instructions and a solution. The solutions have been checked against the examples in the text.

TASK 01Difficulty: medium

The warmest moment

Button A measures the temperature and stores it in an array. Button B shows the highest, and buttons A+B the lowest stored temperature. If the array is empty, B and A+B show the X sign.

Example

Output

A, A, A → B shows the highest measured value
TASK 02Difficulty: easy

Average grade

The array contains the grades in one subject: 5, 4, 4, 3, 5. When A is pressed, show the average, rounded to a whole number.

Example

Output

4
TASK 03Difficulty: hard

Repeat the pattern

A memory game: when A+B is pressed, the micro:bit shows a sequence of 4 arrows (left or right). The player repeats the sequence: button A for left, button B for right. After every press the micro:bit checks the answer: on a mistake it shows a sad face, and when the whole sequence has been repeated correctly – a happy face.

Example

Output

after A+B: arrows ←, →, →, ←; the player presses A, B, B, A → happy face
Common mistakes and tips
  • Indexes start from 0: the last element of the array list is list[list.length - 1].
  • In a MakeCode array all elements are of the same type: either numbers or words.
  • Before looking for the largest value, check that the array is not empty.
  • An empty array of numbers in JavaScript is written as let a: number[] = [].

Check your knowledge

Open the quiz

Arrays

1. What is the index of the first element of an array?




2. The array is [8, 3, 6]. What is list[2]?




3. What does list.push(7) do?




4. How do you choose a random element of the array answers?