When designing programs, there are often points where a decision must be made. This decision is known as selection, and is implemented in programming using IF statements.
In programmingThe process of writing computer software., selectionA decision within a computer program when the program decides to move on based on the results of an event. is usually represented by the statementThe smallest element of a programming language which expresses an action to be carried out.IF and ELSE:
IF represents the question
ELSE points to what to do if the answer to the question is false
For example, this simple algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. prints out a different message depending on how old you are. Using IF and ELSE, the steps are:
Ask how old you are
IF you are 70 or older, say “You are aged to perfection!”
ELSE say “You are a spring chicken!”
If this algorithm is tried using 75 as our age, the answer to the question at step 2 is true, so the algorithm tells us to say “You are aged to perfection!”
If the algorithm is tried using 15 as our age, the answer to the question at step 2 is false, so the algorithm tells us to say “You are a spring chicken!”
Two different paths are followed according to the answer given to a particular question. The flow diagram to illustrate this algorithm is: