S

9.2 Selection

Understanding selection statements in algorithms using pseudocode: IF...THEN...ELSE and CASE...OF statements

Learning Objectives

By the end of this lesson, you will be able to:

  • Write pseudocode using the three basic constructs of sequence, selection and iteration
  • Document simple algorithms using pseudocode
  • Understand and use IF...THEN...ELSE...ENDIF selection statements
  • Understand and use CASE...OF...OTHERWISE...ENDCASE selection statements
  • Create nested IF statements for complex decision making
  • Use appropriate data types (Boolean, Char, String, Real, Integer, Date) in algorithms
  • Apply selection statements to solve real-world problems

Key Terms

Selection

Testing a condition which determines the sequence of execution in an algorithm

Conditional Statement

A statement that performs different actions based on whether a condition is true or false

IF...THEN...ELSE...ENDIF

A selection statement that executes one block of code if condition is true, another if false

CASE...OF...OTHERWISE...ENDCASE

A selection statement that chooses between multiple values/options

Nested IF Statement

An IF statement that contains another IF statement within it

Pseudocode

A simplified, readable way to represent an algorithm without using actual programming syntax

Boolean

A data type that can only have two values: TRUE or FALSE

Integer

A data type for whole numbers without decimal points

Real

A data type for numbers with decimal points

Char

A data type for single characters (letters, digits, symbols)

String

A data type for sequences of characters (text)

Date

A data type for storing dates and times

Selection Statements

Selection is the term used for testing a condition which determines the sequence of execution. When different actions are performed by an algorithm according to values of variables, conditional statements can be used to decide which action should be taken.

Types of Conditional Statements

IF...THEN...ELSE...ENDIF

For an IF condition, the THEN path is followed if the condition is true and the ELSE path is followed if the condition is false. There may or may not be an ELSE path. The end of the statement is shown by ENDIF.

Example 1: Checking Weight
DECLARE weight : Real
INPUT "Enter your weight", weight
IF weight < 20 THEN
    OUTPUT "You are underweight"
ENDIF
Example 2: Age Classification
DECLARE age : Integer
INPUT "Enter your age in years", age
IF age < 18 THEN
    OUTPUT "You are a Child"
ELSE
    OUTPUT "You are an Adult"
ENDIF

CASE...OF...OTHERWISE...ENDCASE

When there are too many available routes in an algorithm, it requires too many IF...THEN...ELSE...ENDIF statements to make a selection among these routes, which is not an easy task and makes the algorithm difficult to manage. To overcome this issue, the CASE...OF...OTHERWISE...ENDCASE statement is used.

CASE Statement Structure
CASE variable OF
    1: Instructions
    2: Instructions
    OTHERWISE
        Instructions
ENDCASE
When to Use Each:

Use IF for true/false conditions, use CASE for multiple specific values/choices.

Visualizing Selection with Flowcharts

IF Statement Flowchart

START
INPUT weight
weight < 20?
TRUE
OUTPUT "Underweight"
FALSE
(Continue Program)
END

How it works: The diamond represents a decision point. Based on whether the condition (weight < 20) is TRUE or FALSE, the program follows different paths. This visual representation helps you understand how selection statements control program flow.

Real-Life Example: Number Guessing Game

A number-guessing game follows different steps depending on certain conditions:

  • Player inputs a number to guess the secret number stored
  • If guess was correct, output a congratulations message
  • If number input was larger than secret number, output message "secret number is smaller"
  • If number input was smaller than secret number, output message "secret number is greater"
DECLARE SecretNum, Guess : Integer
SecretNum ← 30 // SET a value for secret number

INPUT "Enter your guess number", Guess
IF Guess = SecretNum THEN
    OUTPUT "Well done. You have guessed the secret number"
ELSE
    IF Guess > SecretNum THEN
        OUTPUT "secret number is smaller"
    ELSE
        OUTPUT "secret number is greater"
    ENDIF
ENDIF

This is a nested IF statement - an IF statement inside another IF statement, shown clearly by the use of a second level of indentation.

Activity 1: Writing IF Statements

Write pseudocode for the following problems:

  1. Take three numbers as input and output the largest number among them
  2. Take a mark as input (0-100) and print "Pass" if marks are greater than or equal to 50, and "Fail" if they are not
  3. Take a number as input and tell whether the number is even, odd, or zero
Solution:
1. Largest of Three Numbers:
DECLARE num1, num2, num3 : Integer
OUTPUT "Enter Three numbers"
INPUT num1, num2, num3

IF num1 > num2 AND num1 > num3 THEN
    OUTPUT "The largest Number is", num1
ELSEIF num2 > num1 AND num2 > num3 THEN
    OUTPUT "The largest Number is", num2
ELSE
    OUTPUT "The largest Number is", num3
ENDIF
2. Pass/Fail Check:
OUTPUT "Please enter a mark "
INPUT PercentageMark
IF PercentageMark < 0 OR PercentageMark > 100 THEN
    OUTPUT "Invalid Mark"
ELSE
    IF PercentageMark > 49 THEN
        OUTPUT "Pass"
    ELSE
        OUTPUT "Fail"
    ENDIF
ENDIF

A rejected percentage mark must be either less than zero or greater than 100. This is a nested IF statement.

3. Even/Odd/Zero Check:
DECLARE num : Integer
INPUT "Enter a number", num
IF num % 2 = 0 THEN
    OUTPUT "The number is even"
ELSEIF num % 2 = 1 THEN
    OUTPUT "The number is Odd"
ELSE
    OUTPUT "The number is zero"
ENDIF

Check Your Understanding: IF Statements

Answer
  • [1 mark] Testing a condition which determines the sequence of execution
  • [1 mark] When different actions are performed by an algorithm according to values of variables
  • [Additional] Also called conditional or decision statements
Answer
  • [1 mark] The ELSE path executes when the IF condition is FALSE
  • [Additional] If there is no ELSE path and condition is false, the program continues after ENDIF
Answer
  • [1 mark] An IF statement that contains another IF statement within it
  • [1 mark] Used for more complex decision making with multiple conditions
  • [Additional] Shown by indentation levels in pseudocode
Answer
DECLARE grade : Char
INPUT "Enter grade", grade

IF grade = 'A' THEN
    OUTPUT "Excellent"
ELSEIF grade = 'B' THEN
    OUTPUT "Well done"
ELSEIF grade = 'C' THEN
    OUTPUT "You passed"
ELSEIF grade = 'F' THEN
    OUTPUT "Better try again"
ELSE
    OUTPUT "Invalid grade"
ENDIF

Note: This could also be done more efficiently with a CASE statement.

Answer
  • [1 mark] ENDIF marks the end of an IF...THEN...ELSE statement
  • [Additional] It shows where the conditional block ends and normal program execution continues

CASE Statements

When there are too many available routes in an algorithm then it requires too many IF...THEN...ELSE...ENDIF statements to make a selection among these routes which is not an easy task and it makes the algorithm difficult to manage. To overcome this issue, CASE...OF...OTHERWISE...ENDCASE statements are used.

CASE Statement Structure

Basic Syntax

CASE variable OF
    value1: Instructions
    value2: Instructions
    OTHERWISE
        Instructions
ENDCASE
Example: Grade Evaluation
OUTPUT "Enter Your Computer Science Grade"
INPUT grade

CASE grade OF
    'A':
        OUTPUT "Excellent!"
    'B':
        OUTPUT "Well done!"
    'C':
        OUTPUT "You passed!"
    'F':
        OUTPUT "Better try again"
    OTHERWISE
        OUTPUT "Invalid grade"
ENDCASE

Calculator Example

Simple Calculator Program
DECLARE Num1, Num2 : Integer
DECLARE Choice : Char
DECLARE Answer : Float

OUTPUT "Enter two Numbers"
INPUT Num1, Num2

OUTPUT "Enter 1 For addition, 2 For Subtraction, 3 For Multiplication, 4 For Division"
INPUT Choice

CASE Choice OF
    '1': Answer ← Num1 + Num2
    '2': Answer ← Num1 - Num2
    '3': Answer ← Num1 * Num2
    '4': Answer ← Num1 / Num2
    OTHERWISE OUTPUT "Please enter a valid choice"
ENDCASE

OUTPUT "Your result is ", Answer
Note:

CASE statements are cleaner and more readable than multiple IF statements when dealing with multiple specific values.

CASE Statement Simulator

Step through this grade evaluation program to see how a CASE statement works:

CASE grade OF
    'A': OUTPUT "Excellent!"
    'B': OUTPUT "Well done!"
    'C': OUTPUT "You passed!"
    'F': OUTPUT "Better try again"
    OTHERWISE: OUTPUT "Invalid grade"
ENDCASE
1
Input grade value
Select a grade to test:
2
CASE statement evaluation
The program compares the grade with each CASE value
grade = "A"
3
Execute matching CASE
Program jumps to the matching CASE and executes its instructions
Output: "Excellent!"
4
Continue after ENDCASE
Program continues with next statement after ENDCASE
Next statement would execute here...

How CASE works: The program compares the variable value with each CASE value. When it finds a match, it executes that CASE's instructions, then jumps to ENDCASE. If no match is found, it executes the OTHERWISE block.

Important: Understanding Data Types

Data types specify the kind of data that can be stored in a variable. Different data types are used for different purposes in algorithms:

Integer

Whole numbers without decimals

Example: 42, -7, 0

Real

Numbers with decimal points

Example: 3.14, -2.5, 0.0

Boolean

True or False values

Example: TRUE, FALSE

Char

Single character

Example: 'A', '7', '$'

String

Sequence of characters

Example: "Hello", "A123"

Date

Date and time values

Example: 2024-12-25

Choosing the Right Data Type

Always choose the most appropriate data type for your variables:

  • Use Integer for whole numbers (age, count, score)
  • Use Real for measurements (weight, temperature, average)
  • Use Boolean for true/false conditions (isPassed, isLoggedIn)
  • Use Char for single letters (grade, menu choice)
  • Use String for text (name, address, message)
  • Use Date for dates and times (birthday, appointment)

Activity 2: CASE Statement Practice

Solve the following problems using CASE statements:

  1. Write pseudocode that takes three numbers, then asks the user to enter "S" to find the smallest number among them and "L" to find the largest number
  2. Write a program that asks the user to enter two numbers and then perform basic arithmetic operations on them based on user choice
  3. Write a program to check whether a triangle is equilateral, isosceles, or scalene based on three side lengths
Solution:
1. Smallest or Largest Finder:
DECLARE Num1, Num2, Num3 : Integer
DECLARE UserChoice : Char
OUTPUT "Enter three Numbers"
INPUT Num1, Num2, Num3
OUTPUT "Enter 'S' to find smallest number and enter 'L' to find largest number"
INPUT UserChoice

CASE UserChoice OF
    'S':
        IF num1 < num2 AND num1 < num3 THEN
            OUTPUT "Smallest Number is", num1
        ELSEIF num2 < num1 AND num2 < num3 THEN
            OUTPUT "Smallest Number is", num2
        ELSE
            OUTPUT "Smallest Number is", num3
        ENDIF

    'L':
        IF num1 > num2 AND num1 > num3 THEN
            OUTPUT "The largest Number is", num1
        ELSEIF num2 > num1 AND num2 > num3 THEN
            OUTPUT "The largest Number is", num2
        ELSE
            OUTPUT "The largest Number is", num3
        ENDIF

    OTHERWISE: OUTPUT "Invalid Input"
ENDCASE
2. Calculator Program:

(Already shown in the CASE example above)

3. Triangle Type Checker:
DECLARE side1, side2, side3 : Real
OUTPUT "Input length of three sides"
INPUT side1, side2, side3

IF (side1 = side2) AND (side2 = side3) THEN
    OUTPUT "Equilateral triangle"
ELSEIF (side1 = side2) OR (side2 = side3) OR (side1 = side3) THEN
    OUTPUT "Isosceles triangle"
ELSE
    OUTPUT "Scalene Triangle"
ENDIF

Check Your Understanding: CASE Statements

Answer
  • [1 mark] When there are multiple specific values to check against a single variable
  • [1 mark] When the algorithm becomes difficult to manage with too many IF statements
  • [Additional] CASE statements are cleaner, more readable, and more efficient for multiple specific value checks
Answer
  • [1 mark] Executes when none of the CASE values match the variable
  • [1 mark] Acts as a default or fallback option
  • [Additional] Similar to ELSE in an IF statement, but for CASE statements
Answer
DECLARE dayNumber : Integer
INPUT dayNumber

CASE dayNumber OF
    1: OUTPUT "Monday"
    2: OUTPUT "Tuesday"
    3: OUTPUT "Wednesday"
    4: OUTPUT "Thursday"
    5: OUTPUT "Friday"
    6: OUTPUT "Saturday"
    7: OUTPUT "Sunday"
    OTHERWISE: OUTPUT "Invalid day number"
ENDCASE
Answer
  • [1 mark] The program executes the instructions for that CASE
  • [1 mark] Then it jumps to the statement after ENDCASE (doesn't check other cases)
  • [Additional] This is called "fall-through" - once a match is found, only that CASE executes
Answer
  • [0.5 mark each] Boolean, Char, String, Real, Integer, Date
  • [Additional] These data types are used to specify the type of data that is stored in computer memory

Practice Problems

These practice problems combine both IF and CASE statements to solve real-world scenarios. Try to solve them on your own before checking the solutions.

Problem

Problem 1: Even/Odd/Zero Check

Write a program that will ask the user to input a number and print whether the number is even, odd, or zero.

Solution:
DECLARE num : integer
OUTPUT "enter your number "
INPUT num
IF num MOD 2 = 0 THEN
    OUTPUT "Number is even"
ELSEIF num MOD 2 <> 0 THEN
    OUTPUT "Number is odd"
ELSE OUTPUT "number is zero"
ENDIF
Note:

MOD gives the remainder after division. If num MOD 2 = 0, the number is even.

Problem 2: Smallest/Largest Finder

Write pseudocode that takes three numbers, then asks the user to enter "S" to find the smallest number among them and "L" to find the largest number.

Solution:
DECLARE Num1, Num2, Num3 : Integer
DECLARE UserChoice : Char
OUTPUT "Enter three Numbers"
INPUT Num1, Num2, Num3
OUTPUT "Enter 'S' to find smallest number and 'L' to find largest number"
INPUT UserChoice

CASE UserChoice OF
    'S': // Find smallest logic
    'L': // Find largest logic
    OTHERWISE: OUTPUT "Invalid Input"
ENDCASE

Interactive Problem Solver: Triangle Classifier

Enter three side lengths to classify the triangle. The program will determine if it's equilateral, isosceles, or scalene.

Result will appear here
Enter values and click "Classify Triangle"

Algorithm Logic:

IF (side1 = side2) AND (side2 = side3) THEN
    OUTPUT "Equilateral triangle"
ELSEIF (side1 = side2 OR side2 = side3 OR side1 = side3) THEN
    OUTPUT "Isosceles triangle"
ELSE
    OUTPUT "Scalene Triangle"
ENDIF

Real-Life Example: Mobile App Menu System

Mobile apps use selection statements extensively for menu systems and user interactions:

// Mobile banking app menu
DECLARE userChoice : Char
DECLARE balance : Real
balance ← 1000.00

OUTPUT "Banking Menu:"
OUTPUT "1. Check Balance"
OUTPUT "2. Deposit Money"
OUTPUT "3. Withdraw Money"
OUTPUT "4. Exit"
INPUT userChoice

CASE userChoice OF
    '1': OUTPUT "Your balance is: $", balance
    '2': // Deposit logic
    '3': // Withdrawal logic
    '4': OUTPUT "Thank you for banking with us!"
    OTHERWISE: OUTPUT "Invalid choice"
ENDCASE

This shows how CASE statements are perfect for menu-driven programs where users select from multiple options.

Home Task

Take three numbers as input and output the smallest number.

Write pseudocode that takes three numbers as input and outputs the smallest number among them. This is similar to the "largest number" example but you need to find the smallest instead.

Hint:

Modify the "largest number" algorithm by changing the comparison operators from > (greater than) to < (less than). The logic structure remains the same.

Check Your Understanding: Mixed Problems

Answer
  • [1 mark] IF tests true/false conditions; CASE tests for specific values
  • [1 mark] IF can test complex conditions with AND/OR; CASE tests single variable against multiple values
  • [1 mark] CASE is cleaner for multiple specific value checks; IF is better for range checks and complex conditions
  • [Additional] IF uses THEN/ELSE/ENDIF; CASE uses OF/OTHERWISE/ENDCASE
Answer
DECLARE marks : Integer
INPUT "Enter marks (0-100)", marks

IF marks >= 90 AND marks <= 100 THEN
    OUTPUT "Grade: A"
ELSEIF marks >= 80 AND marks <= 89 THEN
    OUTPUT "Grade: B"
ELSEIF marks >= 70 AND marks <= 79 THEN
    OUTPUT "Grade: C"
ELSEIF marks >= 60 AND marks <= 69 THEN
    OUTPUT "Grade: D"
ELSE
    OUTPUT "Grade: F"
ENDIF
Answer
  • [1 mark] When you need to make decisions within decisions
  • [1 mark] For complex conditions that depend on multiple factors
  • [Additional] Example: First check if a student passed (marks >= 50), then if passed, check if they got distinction (marks >= 80)
Answer
  • [1 mark] MOD gives the remainder after integer division
  • [1 mark] Used to check if a number is even (num MOD 2 = 0) or odd (num MOD 2 = 1)
  • [Additional] Example: 7 MOD 2 = 1, 10 MOD 3 = 1, 8 MOD 4 = 0
Answer
DECLARE lightColor : Char
INPUT "Enter traffic light color (R/Y/G)", lightColor

CASE lightColor OF
    'R': OUTPUT "STOP"
    'Y': OUTPUT "GET READY"
    'G': OUTPUT "GO"
    OTHERWISE: OUTPUT "Invalid color"
ENDCASE

This could also be written using IF statements, but CASE is cleaner for specific values.

Key Takeaways

  • Selection is testing a condition to determine the sequence of execution in an algorithm
  • IF...THEN...ELSE...ENDIF is used for true/false conditions - THEN path if true, ELSE if false
  • CASE...OF...OTHERWISE...ENDCASE is used for multiple specific value checks - cleaner than multiple IFs
  • Nested IF statements are IF statements inside other IF statements, used for complex decision making
  • Indentation is crucial in pseudocode to show structure and nesting levels
  • Data types (Boolean, Char, String, Real, Integer, Date) specify what kind of data a variable can store
  • MOD operator gives the remainder after division, used to check even/odd numbers
  • Use IF for range checks and complex conditions with AND/OR operators
  • Use CASE for menu systems and when checking a variable against multiple specific values
  • Always validate input to ensure it's within expected ranges before processing
  • Real-world applications include: grading systems, calculators, traffic lights, menu systems, game logic
  • Practice is essential - write algorithms for different scenarios to master selection statements

Question Bank

Marking Scheme & Answer
  • [2 marks] Purpose: Selection statements test conditions to determine which instructions to execute. They allow algorithms to make decisions and follow different paths based on variable values or user input.
  • [1 mark] Example 1: Checking if a student passed an exam (IF marks >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail")
  • [1 mark] Example 2: A calculator program choosing operation based on user input (CASE choice OF '1': addition, '2': subtraction, etc.)
  • [Additional] Selection is one of the three basic programming constructs along with sequence and iteration.
Marking Scheme & Answer
DECLARE units, bill : Real
INPUT "Enter units consumed", units

IF units <= 100 THEN
    bill ← units * 0.50
ELSEIF units <= 300 THEN
    bill ← (100 * 0.50) + ((units - 100) * 0.75)
ELSE
    bill ← (100 * 0.50) + (200 * 0.75) + ((units - 300) * 1.00)
ENDIF

OUTPUT "Total bill: $", bill

Mark allocation: [1] Variable declaration, [1] Input, [1] First condition, [1] Second condition, [1] Else condition, [1] Output result

Marking Scheme & Answer
IF Statements CASE Statements
Tests true/false conditions Tests for specific values
Uses THEN/ELSE/ENDIF Uses OF/OTHERWISE/ENDCASE
Can test complex conditions with AND/OR Tests single variable against multiple values
Better for range checks (e.g., 0-100) Better for exact value checks (e.g., 'A', 'B', 'C')
Can be nested for complex decisions Cleaner for multiple specific options

Key insight: Use IF when testing conditions (true/false), use CASE when choosing between multiple specific options.

Marking Scheme & Answer
DECLARE storedUser, storedPass, inputUser, inputPass : String
storedUser ← "admin"
storedPass ← "password123"

OUTPUT "Enter username:"
INPUT inputUser
OUTPUT "Enter password:"
INPUT inputPass

IF inputUser = storedUser THEN
    IF inputPass = storedPass THEN
        OUTPUT "Access granted"
    ELSE
        OUTPUT "Wrong password"
    ENDIF
ELSE
    OUTPUT "User not found"
ENDIF

Note: This uses nested IF statements to first check username, then check password if username is correct.

Marking Scheme & Answer
  • [1 mark] Language independent - can be understood by programmers who know different languages
  • [1 mark] Focuses on logic rather than syntax - no need to worry about semicolons, brackets, etc.
  • [1 mark] Easy to read and understand - uses plain English with some structured keywords
  • [1 mark] Quick to write and modify - easy to test algorithms without writing full code
  • [Additional] Helps in planning before coding, reduces errors, facilitates communication between team members
Marking Scheme & Answer
DECLARE choice : Integer
DECLARE price, money, change : Real

OUTPUT "Select drink: 1-Coke($1), 2-Pepsi($1), 3-Water($0.5), 4-Juice($1.5)"
INPUT choice

CASE choice OF
    1: price ← 1.00
    2: price ← 1.00
    3: price ← 0.50
    4: price ← 1.50
    OTHERWISE: OUTPUT "Invalid choice"
ENDCASE

OUTPUT "Price is $", price, ". Insert money:"
INPUT money

IF money >= price THEN
    change ← money - price
    OUTPUT "Dispensing drink. Change: $", change
ELSE
    OUTPUT "Insufficient money. Need $", price - money, " more."
ENDIF
Marking Scheme & Answer
  • [2 marks] Definition: Nested IF statements are IF statements that contain other IF statements within them. They are used when decisions depend on multiple conditions in a hierarchical manner.
  • [2 marks] Example:
    IF age >= 18 THEN
        IF hasLicense = TRUE THEN
            OUTPUT "Can drive"
        ELSE
            OUTPUT "Needs license"
        ENDIF
    ELSE
        OUTPUT "Too young to drive"
    ENDIF
Marking Scheme & Answer
DECLARE a, b, c, D, root1, root2 : Real
OUTPUT "Enter coefficients a, b, c:"
INPUT a, b, c

D ← (b * b) - (4 * a * c)

IF D > 0 THEN
    root1 ← (-b + SQRT(D)) / (2 * a)
    root2 ← (-b - SQRT(D)) / (2 * a)
    OUTPUT "Two real roots: ", root1, " and ", root2
ELSEIF D = 0 THEN
    root1 ← -b / (2 * a)
    OUTPUT "One real root: ", root1
ELSE
    OUTPUT "No real roots (complex roots)"
ENDIF
Marking Scheme & Answer
  • [1 mark] The OTHERWISE clause provides a default action to execute when none of the CASE values match the variable being tested
  • [1 mark] It handles unexpected or invalid input values gracefully
  • [Additional] Similar to the ELSE clause in an IF statement, but specifically for CASE statements when no matching case is found
Marking Scheme & Answer
DECLARE balance, amount : Real
DECLARE choice : Integer
balance ← 1000.00 // Initial balance

REPEAT
    OUTPUT "ATM Menu: 1-Check Balance, 2-Withdraw, 3-Deposit, 4-Exit"
    INPUT choice

    CASE choice OF
        1: OUTPUT "Current balance: $", balance

        2:
            OUTPUT "Enter amount to withdraw:"
            INPUT amount
            IF amount <= balance THEN
                balance ← balance - amount
                OUTPUT "Withdrawal successful. New balance: $", balance
            ELSE
                OUTPUT "Insufficient funds"
            ENDIF

        3:
            OUTPUT "Enter amount to deposit:"
            INPUT amount
            balance ← balance + amount
            OUTPUT "Deposit successful. New balance: $", balance

        4: OUTPUT "Thank you for using our ATM"
        OTHERWISE: OUTPUT "Invalid choice"
    ENDCASE

UNTIL choice = 4

Note: This uses a REPEAT...UNTIL loop (iteration) to keep showing the menu until user chooses to exit. This combines selection with iteration.