Programs that Remember and Choose

Tracing a loop with a total

Trace a loop that keeps a running total, and say what the total holds once the loop has finished.

A running total is a variable a loop keeps adding to. It is the reason loops and variables belong in the same lesson: on its own a loop repeats an action and leaves nothing behind, and a running total is how the repetitions add up to an answer. Every one of these programs has the same three parts — a line that sets the total before the loop, a loop that changes it, and a line that shows it afterwards.

Inside the loop or after it

Where a line sits decides how often it runs, and this is the single thing worth being careful about. A line inside the loop runs once for every time round. A line after the loop runs once, whatever the loop did. And the line that sets the total goes before the loop for the same reason: put it inside, and the total would be wiped clean at the start of every time round, so the program would finish with only the last step's worth of anything.

Worked example

A program says: set total to 0; repeat 3 times: add 9 to total; then print total. What does it show?

  1. Before the loop, total is 0.

    A running total has to start somewhere, and starting at nothing is what makes the finishing value the sum of what the loop added.

Try it together

Now trace this one together: set total to 5; repeat 4 times: add 3 to total.

Say what the total holds after each time round.

    1.What does total hold after the first time round?

    Have a go

    Have a go on your own. A program says: set total to 3; repeat 4 times: add 5 to total. What does total hold at the end?

    Ready to practice?

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

    Print a worksheet