Night 6: Your pet's favourite snacks
You already finished this night, in Python or pseudocode. It counts for both. Practise again if you like.
Tonight: an array of snacks
- Your pet likes many snacks. One variable for each? Too many!
- You will learn one thing: arrays.
Words for tonight
| Word | Meaning |
|---|---|
| array | many values of the same type in one variable, in order |
| element | one value in an array |
| index | the number of a place in the array; here it starts at 1 |
Make an array
ARRAY[1:3]makes 3 places, numbered 1, 2 and 3.OF STRINGsays each place keeps text.- The size never changes. Make it big enough at the start.
DECLARE Snacks : ARRAY[1:3] OF STRING
Snacks[1] ← "apple"
Snacks[2] ← "rice"
Snacks[3] ← "fish"
OUTPUT Snacks[1]
The index is in square brackets
| Index | 1 |
2 |
3 |
|---|---|---|---|
| Element | "apple" |
"rice" |
"fish" |
- Write the index in square brackets after the name:
Snacks[2]is"rice". OUTPUTshows one element at a time.OUTPUT Snacksdoes not work.
DECLARE Snacks : ARRAY[1:3] OF STRING
Snacks[1] ← "apple"
Snacks[2] ← "rice"
Snacks[3] ← "fish"
OUTPUT Snacks[1]
OUTPUT Snacks[2]
![The array Snacks holds apple, rice, fish at indexes 1, 2, 3; ARRAY[1:4] leaves room for cake at index 4](/static/code/nights-pseudocode/06-array.png)
Room for one more
- An array cannot grow. To add a snack later, make the array bigger at the start.
ARRAY[1:4]has room for 4 snacks. Fill the empty place when you need it.
DECLARE Snacks : ARRAY[1:4] OF STRING
Snacks[1] ← "apple"
Snacks[2] ← "rice"
Snacks[3] ← "fish"
Snacks[4] ← "cake"
OUTPUT Snacks[4]
Change one element
- Put a new value at an index with
←.
DECLARE Snacks : ARRAY[1:3] OF STRING
Snacks[1] ← "apple"
Snacks[2] ← "rice"
Snacks[3] ← "fish"
Snacks[1] ← "pear"
OUTPUT Snacks[1]
- Careful:
Snacks[4]is an error here. The array has only the places 1 to 3.
Now you try
- Do the tasks below. Press Run, then Check answer.
- Tomorrow your pet will use this array in a loop.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The array Snacks has 3 places. Put "apple" at index 1, "rice" at index 2 and "fish" at index 3.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Output the 第一个 snack, then the 最后一段 snack. The output is apple and then fish, on two lines. Use the array, not the words.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Your pet found a new snack. The array has room for 4 snacks, and place 4 is still empty. Put "cake" in the last place. Then output the last snack. The output is cake.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Your pet does not like rice any more. Change the 秒 element to "noodles". Then output all three snacks, one per line: apple, noodles, fish.
点击“运行”查看此处输出。