Programs that Remember and Choose

Choosing between more than two things

Follow a chain of tests in which the first one that comes out true wins, and say which branch a program takes.

An if with an otherwise gives a program two paths, and two is often not enough. A chain is what you write when there are more: a first test, then any number of else-if tests, then an otherwise at the end to catch whatever is left. It reads from the top down, and the program leaves the chain the moment something matches.

The first match wins, and the rest never run

This is what makes a chain different from a pile of separate ifs. Once a test comes out true, its branch runs and every test below it is skipped without ever being looked at — so a chain always takes exactly one branch, however many of its tests would have been true. Which means the order the tests are written in is part of what the chain means, and not just a matter of tidiness.

Worked example

A bus fare depends on age. The program says: if the age is at least 60, charge nothing; else if the age is at least 12, charge full fare; otherwise charge half fare. What is charged for someone aged 65?

  1. Take the first test on its own: is 65 at least 60? Yes.

    A chain is only ever read downwards, so the first test is the only one that can be reached without conditions.

Try it together

Now work through this chain together: if the length is more than 50, print "Long"; else if the length is more than 20, print "Medium"; otherwise print "Short". The length is 20.

Take one test at a time and say whether it holds.

    1.Is 20 more than 50? Answer yes or no.

    Have a go

    Have a go on your own. A program says: if the mark is at least 75, print "Distinction"; else if the mark is at least 33, print "Pass"; otherwise print "Fail". The mark is 33. What does it print?

    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