Selection
Selection
There are two methods of selecting which code from a choice of code will be executed, IF and CASE. We will look at the IF construction first followed by the CASE construction.
IF-THEN-ELSE-ENDIF
Look at the following example:
INPUT letter using keyboard
IF (Letter entered = P) THEN
Do the code in here - call it block A
ELSE
Do the code in here - call it block B
ENDIF
When this code is run, the program waits for the user to enter a letter via the keyboard. When the letter has been entered, it is checked. If the letter P were entered, for example, then the instructions in block A would be executed. If the letter entered was not a P, then the instructions in block B would be done. The construction then ends and the next instruction in the sequence is done.
Nested IF-THEN-ELSE-ENDIF
Not only can you make selections using the IF construct, you can also put them inside each other! When we do this, we say that the IF instructions are nested. Nesting is a very useful technique so long as the code is laid out correctly and you don’t use too many nested IF statements.
Consider this example that uses nested IF statements.
INPUT ExamMark
IF (ExamMark < 40) THEN
PRINT "You have failed."
ELSE
IF (ExamMark < 60) THEN
PRINT "You have passed."
ELSE
IF (ExamMark < 70) THEN
PRINT "You have passed with a merit."
ELSE
IF (ExamMark <80) THEN
PRINT "You have passed with a distinction."
ELSE
PRINT "Outstanding! You have passed with honours!"
ENDIF
ENDIF
ENDIF
ENDIF
CASE
You have probably worked out that nested IF statements are fine in moderation, but too many and the code can become hard to follow. Fortunately, there is another type of selection construct that can be used. It usually involves checking instances of variables. Consider this example.
CASE (variable) OF
Do these instructions if a is selected;
Do these instructions if b is selected;
Do these instructions if c is selected;
Do these instructions if d is selected;
Do these instructions if e is selected;
Do these instructions if f is selected;
ELSE
Do these instructions;
ENDCASE
If the variable used holds an ‘a’, then you do the instructions after ‘a’ and then jump to ENDCASE. If it is a ‘b’, then you do the instructions after ‘b’ and then jump to ENDCASE, and so on. If it is not any of ‘a’ to ‘f’, then you do the instructions in the ELSE part of the construct and then jump to ENDCASE.
This is very convenient. Some languages don’t use CASE, though. Python has a construct IF – ELIF – ELIF – ELIF – ELSE, which can be used just like a CASE statement so it is something to look out for. The ELIF (ELSE IF) can be used as many times as needed to test a particular variable.