The ELSE IF instruction
The ELSE IF instruction allows there to be more than two paths through an algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs.. Any number of ELSE IF instructionA single action that can be performed by a computer processor. can be added to an algorithm. It is used along with other instructions:
- IF represents a question
- THEN points to what to do if the answer to the question is true
- ELSE IF represents another question
- THEN points to what to do if the answer to that question is true
- ELSE IF represents another question
- THEN points to what to do if the answer to that question is true
- ELSE points to what to do if the answer to the question is false
Using this method, the bus fare algorithm could be improved like this:
- ask how old you are
- IF you are under 5, THEN pay no fare
- ELSE IF you are under 16, THEN pay half fare
- ELSE IF you are an OAP, THEN pay no fare
- ELSE pay full fare
As this algorithm uses ELSE IF statements, a 14 year old would stop at step 3. However, if the algorithm was made up of three different IF statements, the same 14 year old would have to check to see if they were an OAP (step 4) even though they had already found the correct option for themselves.
ELSE IF is covered in more detail in Selection in programming.