micro:bit(SR) → MakeCode(SR) → Arrays on the micro:bit: lists of numbers and words in MakeCode
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
Index
0
1
2
3
Value
5
4
5
3
An element is changed like an ordinary variable: grades[1] = 5 (the block set value at).
Adding and removing elements
Block
JavaScript
What it does
add value to end
list.push(x)
adds x to the end of the array
get and remove last value
list.pop()
removes the last element and returns it
remove value at
list.removeAt(i)
removes the element with index i
find index of
list.indexOf(x)
index of the first occurrence of x (−1 if it is not there)
length of array
list.length
number 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
Instructions
Look for the largest value with a for element loop, as in the example with points; let the starting value be the first element of the array.
Solution (JavaScript in MakeCode)
let temp: number[] = []
input.onButtonPressed(Button.A, function () {
temp.push(input.temperature())
basic.showNumber(temp.length) // how many measurements we have
})
input.onButtonPressed(Button.B, function () {
if (temp.length == 0) {
basic.showIcon(IconNames.No)
} else {
let max = temp[0]
for (let t of temp) {
if (t > max) {
max = t
}
}
basic.showNumber(max)
}
})
input.onButtonPressed(Button.AB, function () {
if (temp.length == 0) {
basic.showIcon(IconNames.No)
} else {
let min = temp[0]
for (let t of temp) {
if (t < min) {
min = t
}
}
basic.showNumber(min)
}
})
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
Instructions
The sum is 21 and there are 5 grades; the average 4.2 rounded is 4. Use Math.round.
Solution (JavaScript in MakeCode)
let grades = [5, 4, 4, 3, 5]
input.onButtonPressed(Button.A, function () {
let sum = 0
for (let g of grades) {
sum += g
}
basic.showNumber(Math.round(sum / grades.length))
})
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
Instructions
Remember the array pattern and the counter step. In the button A event compare pattern[step] with 1, in the button B event with 2. If it is wrong – sad face; if step has reached 4 – happy face.
Solution (JavaScript in MakeCode)
let pattern: number[] = []
let step = 0
function check (pressed: number) {
if (step >= pattern.length) {
return // the game has not started or is over
}
if (pattern[step] == pressed) {
step += 1
if (step == pattern.length) {
basic.showIcon(IconNames.Happy) // all correct
}
} else {
basic.showIcon(IconNames.Sad) // mistake
step = pattern.length // end of the game
}
}
input.onButtonPressed(Button.AB, function () {
pattern = []
for (let i = 0; i < 4; i++) {
pattern.push(randint(1, 2))
}
for (let p of pattern) {
if (p == 1) {
basic.showArrow(ArrowNames.West)
} else {
basic.showArrow(ArrowNames.East)
}
basic.pause(300)
basic.clearScreen()
basic.pause(200)
}
step = 0
})
input.onButtonPressed(Button.A, function () {
check(1)
})
input.onButtonPressed(Button.B, function () {
check(2)
})
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?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.