AdvertisementYour brand could be hereYour brand hereOn every Darslab page · students, parents and teachersinfo@darslab.comAsk for pricesPricesinfo@darslab.com
☰ Year plan · Computing

Variables and values

Week 8 · Unit 4: Be a storyteller · 3 lessons
3

Variables change as a program runs

Computing 5: Unit 4, pp. 44–57
GoalUse ‘set’ and ‘change’ blocks with a variable and trace its value step by step.
New words
set · to give a variable a value, such as 0, at a chosen momentchange · to add to the variable’s present value; a negative number takes awayincrease · to make a value biggerdecrease · to make a value smaller
Explanation

Two blocks work on variables. The block ‘set (stars) to 0’ gives the variable a value, no matter what it held before. The block ‘change (stars) by 3’ adds 3 to the present value. To take away, we change by a negative number, such as −1. Programs normally set a variable when the green flag is clicked, so that every game starts in the same way. To trace a program, write down the value of the variable after each step. The value of a variable can increase, decrease or stay the same. A trace table shows how it grows and shrinks.

Starwhenclickedsetstarsto0Starwhen this sprite clickedchangestarsby3
Worked examples
Clicksstars
0 (after the flag)0
13
26
39
412
The star adds 3 each time that it is clicked. The value of stars begins at 0. After four clicks the value is 12.
whenclickedsetlivesto3changelivesby-1repeat2
A lives counter goes down. It is set to 3 and then reduced by 1 twice. The value goes from 3 to 2 and then to 1.
Without a ‘set’ block at the start, the variable keeps its old value. If the stars were 12 at the end of the last game, the next game starts at 12, and one click gives 15 and not 3. That is why we set the variable when the flag is clicked.
Class activity

Cup and counters (2 players, a cup and about 20 counters or beans). The counters in the cup are the value of a variable. ‘Set to 5’ means empty the cup and put in exactly 5. ‘Change by 3’ means add 3 more. ‘Change by −2’ means take out 2. One player reads a short program aloud and the other follows it with the cup. Write the value after every step. Check the final value by counting. Then make up your own program for your partner.

Practice
1
Trace this program. What is the value of coins at the end?
setcoinsto5changecoinsby2changecoinsby-3changecoinsby4
2
In the star program from the lesson, each click adds 3 to stars, and the flag sets stars to 0. How many clicks are needed to reach at least 20?
3
Show the value of lives after each step of this program.
setlivesto3changelivesby-1repeat3
4
The variable bottles starts at 10. It goes down by 2 when a sprite is clicked. What is its value after 3 clicks? Write the two scripts in words.