Selection in practice: How old are you?
algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. consist of a set of instructionA single action that can be performed by a computer processor. that are carried out (performed) one after another. Sometimes there may be more than one path (or set of steps) that can be followed. At this point, a decision needs to be made. This point is known as selection.
For example, a simple algorithm can be created to determine correct bus fares. The steps could be:
- ask how old you are
- if you are under 16, pay half fare
- otherwise pay full fare
The decision comes in step 2. If you are aged less than 16, one fare is charged. Otherwise, a different fare is charged.
…Tᷡ…E
Selection allows several paths to be included in an algorithm. In algorithms (and in programming), selection is usually represented by the instructions IF, THEN and ELSE.
- IF represents the question
- THEN points to what to do if the answer to the question is true
- ELSE points to what to do if the answer to the question is false
Using this method, the fare-related algorithm now reads like this:
- ask how old you are
- IF you are under 16, THEN pay half fare
- ELSE pay full fare
If you try this algorithm using 15 as your age, the answer to the question at step 2 is true, so the algorithm tells you to pay half fare.
If you try the algorithm using 16 as your age, the answer to the question at step 2 is false, so the algorithm tells us to pay full fare.
Two different paths are followed according to the answer given to a particular question.