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
Example 2: Age Classification
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
Use IF for true/false conditions, use CASE for multiple specific values/choices.
Visualizing Selection with Flowcharts
IF Statement Flowchart
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"
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:
- Take three numbers as input and output the largest number among them
- 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
- Take a number as input and tell whether the number is even, odd, or zero
Solution:
1. Largest of Three Numbers:
2. Pass/Fail Check:
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:
Check Your Understanding: IF Statements
1. What is selection in programming? [2 marks]
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
2. When does the ELSE path execute in an IF statement? [1 mark]
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
3. What is a nested IF statement? [2 marks]
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
4. Write pseudocode to check if a student's grade is A, B, C, or F. [3 marks]
Answer
Note: This could also be done more efficiently with a CASE statement.
5. What is the purpose of ENDIF? [1 mark]
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
Example: Grade Evaluation
Calculator Example
Simple Calculator Program
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:
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:
- 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
- Write a program that asks the user to enter two numbers and then perform basic arithmetic operations on them based on user choice
- Write a program to check whether a triangle is equilateral, isosceles, or scalene based on three side lengths
Solution:
1. Smallest or Largest Finder:
2. Calculator Program:
(Already shown in the CASE example above)
3. Triangle Type Checker:
Check Your Understanding: CASE Statements
1. When should you use a CASE statement instead of multiple IF statements? [2 marks]
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
2. What does the OTHERWISE clause do in a CASE statement? [2 marks]
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
3. Write a CASE statement that outputs days of the week based on numbers 1-7. [3 marks]
Answer
4. What happens after a matching CASE is executed? [2 marks]
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
5. List six common data types used in pseudocode. [3 marks]
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:
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:
Interactive Problem Solver: Triangle Classifier
Enter three side lengths to classify the triangle. The program will determine if it's equilateral, isosceles, or scalene.
Algorithm Logic:
Real-Life Example: Mobile App Menu System
Mobile apps use selection statements extensively for menu systems and user interactions:
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
1. What is the difference between IF and CASE statements? [3 marks]
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
2. Write pseudocode to calculate a student's grade based on marks. [4 marks]
A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: Below 60
Answer
3. When would you use nested IF statements? [2 marks]
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)
4. What is the MOD operator and how is it used? [2 marks]
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
5. Write pseudocode for a traffic light system. [3 marks]
Red: Stop, Yellow: Get ready, Green: Go
Answer
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
1. Explain the purpose of selection statements in algorithms. Provide two examples. [4 marks]
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.
2. Write pseudocode for a program that calculates electricity bill based on units consumed. [6 marks]
First 100 units: $0.50 per unit
Next 200 units: $0.75 per unit
Above 300 units: $1.00 per unit
Marking Scheme & Answer
Mark allocation: [1] Variable declaration, [1] Input, [1] First condition, [1] Second condition, [1] Else condition, [1] Output result
3. Compare and contrast IF statements and CASE statements. [5 marks]
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.
4. Write pseudocode for a simple login system. [5 marks]
Check username and password. If both correct: "Access granted".
If username correct but password wrong: "Wrong password".
If username doesn't exist: "User not found".
Marking Scheme & Answer
Note: This uses nested IF statements to first check username, then check password if username is correct.
5. What are the advantages of using pseudocode over actual programming code when designing algorithms? [4 marks]
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
6. Write pseudocode for a vending machine that sells drinks. [6 marks]
Options: 1-Coke ($1), 2-Pepsi ($1), 3-Water ($0.5), 4-Juice ($1.5)
Ask user to select drink and insert money. Calculate change or ask for more money.
Marking Scheme & Answer
7. Explain what nested IF statements are and provide an example. [4 marks]
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 THENIF hasLicense = TRUE THENOUTPUT "Can drive"ELSEOUTPUT "Needs license"ENDIFELSEOUTPUT "Too young to drive"ENDIF
8. Write pseudocode to find the roots of a quadratic equation. [6 marks]
ax² + bx + c = 0. Calculate discriminant D = b² - 4ac.
If D > 0: two real roots, D = 0: one real root, D < 0: no real roots.
Marking Scheme & Answer
9. What is the purpose of the OTHERWISE clause in a CASE statement? [2 marks]
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
10. Design an algorithm for a simple ATM machine. [8 marks]
Options: 1-Check Balance, 2-Withdraw, 3-Deposit, 4-Exit
Include validation for insufficient funds during withdrawal.
Marking Scheme & Answer
Note: This uses a REPEAT...UNTIL loop (iteration) to keep showing the menu until user chooses to exit. This combines selection with iteration.