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

Variables hold data

Week 8 · Unit 4: Variables in programming · 3 lessons
3

Starting values and changes

Computing 6: Unit 4, pp. 52–67
GoalSet variables to starting values and tell the blocks set and change apart.
New words
initialise · to give a variable its starting valueset · to replace the value in a variable with a new valuechange by · to add a number to the old value of a variabletrace table · a table that shows the values of variables after each step
Explanation

A program can have as many variables as it needs, and each one holds different data. When the program begins, we usually give every variable a starting value, often 0. This is called initialising. It clears any old data left from the last time the program ran. After that, two kinds of step change a variable. The step set replaces the old value with a new one. The step change by adds a number to the old value, and a negative number takes away. A trace table helps you follow what happens. It shows each variable as a column and each step as a row.

whenclickedsetscoreto0setmovesto0changescoreby5changemovesby1
Worked examples
Stepscoremoves
set score to 00—
set moves to 000
change score by 550
change moves by 151
This is the trace table for the blocks in the picture above. The two variables are set to 0 first, and then each one changes.
Blockscore beforescore after
set score to 252
change score by 257
Set and change are not the same. The variable score holds 5. After set score to 2, it holds 2. After change score by 2, it holds 7.
In Scratch you can make a variable for all sprites, so that every sprite can use it, or for this sprite only. A score that every sprite needs to share is a variable for all sprites.
Class activity

Cup game (no computer): label three cups score, turns and bonus. Put 0 counters in each. Roll a die five times. After each roll, change score by the number rolled, change turns by 1, and if the roll is 6 change bonus by 1. Write a trace table on paper with a row after each roll. After five rolls, what are the three values? Play again, but forget to reset the cups. What goes wrong? If you have a computer or tablet, build the same program in Scratch.

Practice
1
Complete the trace table. The steps are: set a to 4, set b to 9, set total to a + b, change a by 1, set total to a + b.
Stepabtotal
set a to 44——
set b to 949—
set total to a + b49?
change a by 1?913
set total to a + b59?
2
The variable score holds 5. What does it hold after each script?
Script Asetscoreto2Script Bchangescoreby2
3
Why do programs often set every variable to 0 when the green flag is clicked?
4
Tom wants to store a pupil’s first name, age and class letter. Name three variables and their data types.