Click to see the rest of the programming section :
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.
Try it for yourself with the code below. Extend the Python 3 code to match the algorithm. Press Ctrl + Enter (Cmd + Enter on Mac) when you want to run the code.
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.
Find this page helpful? Share the love on your social media mentioning @TeachAllAboutIT and we’ll enter you in our monthly draw to win a gift voucher for any product on the site!
More For Members
Sign Up For Membership Today
|Individual Teacher||£3.99 per Month. After your initial payment, your first payment is Free.||Select|
|Individual Student||£2.50 per Month. After your initial payment, your first payment is Free.||Select|
|Whole School||£12.50 per Month.||Select|
|iGCSE Computer Science Distance Learning (Feb Start)||£21.00 now and then £21.00 per Month for 15 more Months.||Select|
|iGCSE Computer Science Distance Learning (Sept Start)||£21.00 now and then £21.00 per Month for 15 more Months.||Select|