Programs that Remember and Choose

Variables in a program

Follow what a named value holds as a program changes it line by line, and say what it holds at the end.

Until now a program has done its work and thrown the result away. A variable is how it keeps one. A variable is a name with a value attached, and a program can set it, read it, and set it again as often as it likes — which is what lets a program of ten lines do work that would otherwise need ten separate answers written down on paper.

One value at a time

A name holds exactly one value, and setting it again throws the old one away without asking. Two things follow, and nearly every mistake in this topic is one of them. A line like set n to n plus 1 is not a claim that n equals n plus 1 — it works out the right-hand side using what n holds now, and then stores that as the new n. And a line that only reads a variable, such as printing it, leaves it exactly as it was.

Worked example

A program says: set p to 7; set q to 2; set p to p minus q; print p; print q. What does it show?

  1. Write the two names down with their first values: p is 7, q is 2.

    Keeping a written list of the names is the whole technique. Everything after this is crossing one out and writing another.

Try it together

Now trace this one together: set j to 4; set k to j; add 5 to j; print k.

Keep a written list of the two names and update it line by line.

    1.After the second line, what does k hold?

    Have a go

    Have a go on your own. A program says: set t to 15; take 5 away from t; add 2 to t. What does t hold now?

    Ready to practise?

    Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.

    Print a worksheet