In programming we often need to tell the computer whether to run a section of code, or to skip it. For example, when we run a Bubble Sort, we want to increase the swap counter by 1 if two numbers are swapped over, but if they’re not we want to ignore that line of code. This is where selection comes in.
Selective statements come in two forms: IF, THEN, ELSE and CASE.
In fact, both of these statements work in very similar ways, but the IF statement becomes inefficient as it gets longer. But why?
Imagine that you wanted to look at the value of a variable to see what fruit you had and output a specific statement for each. An IF statement would look at each one in turn then run the line of code that matched the true condition. In pseudocode, this looks something like:
IF fruit = Banana THEN
ELSE IF fruit = Apple THEN
ELSE IF fruit = Strawberry THEN
OUTPUT “I don’t know that fruit”
The code in this case checks the condition in the top statement to see if it is true, if it isn’t it will check the next one down, then the next, and so on until it reaches the ELSE which catches everything else.
A CASE statement is similar to this, but instead of testing a condition for each one from the top down, it will go directly to the correct statement and run the code in that block. In pseudocode this looks like this:
CASE fruit of:
Banana: OUTPUT “Yellow”
Apple: OUTPUT “Green”
Strawberry: OUTPUT “Red”
DEFAULT: “I don’t know that fruit”
Notice how they so really similar things, but the CASE statement is much shorter and clearer? So why don’t we use them everywhere? Well, unless there are more than two ELSE IF statements, it doesn’t make much difference and certain languages (like Python) don’t actually contain a CASE statement within the syntax. In those cases, we must stick to long ELSE IF statements, but be aware that a CASE would have been a better choice.