Tutorial 6
❓
Selection: IF & CASE
0984 IGCSE
Often, we want to choose what code executes based on some conditions at runtime - for this, we can use the following selection statements
- IF: code inside block will be executed if IF condition evaluates to TRUE. IF statements can be used for any type of condition, but require more code than CASE statements
- CASE: offers more concise syntax for checking individual, multiple values or finite ranges (INTEGERs or CHARs)
1
IF Statements
Let's see how to write a simple IF statement
2
Nested IFs
Note: the syllabus doesn't support ELSE IF, hence you have to nest IF statements inside the ELSE blocks if you want to check multiple conditions
This means that every IF statement should have a corresponding ENDIF - i.e. if you have 5 IFs, then you need 5 ENDIFs
3
CASE Statements
As can be seen, nested IFs can get long quite quickly - in the following cases, we can use CASE statements to offer more concise syntax:
- to check individual values
- to check multiple values, separated by a comma ,
- to check a finite range of INTEGER or CHAR values using TO
Note: in the syllabus document, only the first option is officially listed, however many past paper questions and mark schemes use the latter two as well, so it should be fine to use them in the exam
If none of the values equal the value you are checking, then the OTHERWISE keyword can be used to define the code that gets executed
Some students think you can only have a single line/statement for each case condition - but as you can see in the OTHERWISE block, we can have as many lines as we want inside each condition
4
User Login
Create a program that stores the real username and password in two variables - then asks the user to enter their username/password - if correct, a "Login" message should be displayed, else, appropriate "Username incorrect" or "Password incorrect" message should be displayed
5
Number, Lowercase, Uppercase
Prompt the user to enter a single character, then output if the character they entered is a number, lowercase letter, uppercase letter or other
6
Number Challenge
Create a program that asks a user to enter 2 numbers, then outputs "Success" if a * b is 5x greater than a + b - if not, then "Failure" will be output
Hint: a * b = 100 works for this - would what be the values of a and b?