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.
Worked examples
Step
score
moves
set score to 0
0
—
set moves to 0
0
0
change score by 5
5
0
change moves by 1
5
1
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.
Block
score before
score after
set score to 2
5
2
change score by 2
5
7
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.
Step
a
b
total
set a to 4
4
—
—
set b to 9
4
9
—
set total to a + b
4
9
?
change a by 1
?
9
13
set total to a + b
5
9
?
After set total to a + b the first time, total is 13. After change a by 1, a is 5. After the last step, total is 5 + 9 = 14.
2
The variable score holds 5. What does it hold after each script?
After script A, score holds 2. After script B, score holds 7.
3
Why do programs often set every variable to 0 when the green flag is clicked?
It clears the old values from the last time the program ran, so each run starts fresh.
4
Tom wants to store a pupil’s first name, age and class letter. Name three variables and their data types.
For example: firstName (string), age (integer) and classLetter (character).