Learning Objectives
By the end of this lesson, you will be able to:
- Write pseudocode using IF statements including ELSE clause and nested IF statements
- Write pseudocode using CASE structures
- Write pseudocode for count-controlled (FOR) loops
- Write pseudocode for post-condition (REPEAT-UNTIL) loops
- Write pseudocode for pre-condition (WHILE-DO) loops
- Justify why one loop structure may be better suited to solve a problem than others
- Apply selection and iteration constructs to solve real-world programming problems
Exam Focus: These constructs are essential for Paper 2 pseudocode questions and practical programming.
Key Terms
Selection
Changing program flow based on conditions. Used for validation, calculation, and user choices.
IF Statement
Executes instructions if a condition is true. Can include ELSE clause for alternative execution.
CASE Statement
Compares multiple values of the same variable. Useful for menu systems and multiple choices.
Iteration
Repeating a line or block of code using a loop. Also called looping or repetition.
Count-controlled Loop
Repeats code a fixed number of times (e.g., FOR loop). Knows iterations in advance.
Condition-controlled Loop
Repeats code until a condition is met. Includes WHILE (pre-condition) and REPEAT (post-condition).
Pre-condition Loop
Checks condition before execution (WHILE-DO). May run 0 or more times.
Post-condition Loop
Checks condition after execution (REPEAT-UNTIL). Always runs at least once.
Nested Statements
Statements within other statements (e.g., IF inside IF, loop inside loop).
Section 1: Selection Constructs
Selection is when the flow of a program is changed, depending on a set of conditions. The outcome determines which lines of code run next. Selection is used for validation, calculation, and making sense of user choices.
What is Selection?
There are two ways to write selection statements: IF...THEN...ELSE... and CASE... statements.
IF Statements
Basic IF Syntax
Conditions must evaluate to TRUE or FALSE. Use comparison operators: =, <, >, <=, >=, <> (not equal).
Example: Weather Check
Nested IF Statements
Nested IF statements are an IF statement within another IF statement. "Nested" means to be 'stored inside the other'.
1. Check if Player2Score > Player1Score
2. If TRUE: Check if Player2Score > HighScore
- If TRUE: Output champion and highest scorer
- If FALSE: Output champion only
3. If FALSE: Player1 is champion, check if also highest scorer
IF Statement Simulator
Test different conditions to see how IF statements work. Change the values and observe the output.
Input Values:
Program Output:
CASE Statements
CASE Statement Structure
Use when comparing multiple values of the SAME variable. IF statements are more flexible for complex conditions.
Example: Direction Check
Activity 1: Selection Practice
Difficulty: Easy • Time: 10 minutes
Write pseudocode for these scenarios:
- Write pseudocode that checks if a number is positive, negative, or zero using IF statements.
- Convert the weather example from IF to CASE statement.
- Write pseudocode for a simple calculator that takes two numbers and an operator (+, -, *, /) and performs the calculation using CASE.
- Write nested IF statements to determine a student's grade: A (≥90), B (80-89), C (70-79), D (60-69), F (<60).
Solution:
-
INPUT numberIF number > 0 THENOUTPUT "Positive"ELSEIF number < 0 THENOUTPUT "Negative"ELSEOUTPUT "Zero"ENDIF
-
CASE OF weather"sunny" : OUTPUT "Don't forget your sunglasses!""rainy" : OUTPUT "Take an umbrella with you.""snowy" : OUTPUT "Wear warm clothes!"OTHERWISE: OUTPUT "Not sure what to suggest"ENDCASE
-
INPUT num1, num2, operatorCASE OF operator"+" : OUTPUT num1 + num2"-" : OUTPUT num1 - num2"*" : OUTPUT num1 * num2"/" : OUTPUT num1 / num2OTHERWISE: OUTPUT "Invalid operator"ENDCASE
-
INPUT scoreIF score >= 90 THENOUTPUT "A"ELSEIF score >= 80 THENOUTPUT "B"ELSEIF score >= 70 THENOUTPUT "C"ELSEIF score >= 60 THENOUTPUT "D"ELSEOUTPUT "F"ENDIF
Check Your Understanding: Selection
1. What is the purpose of selection in programming? [2 marks]
Answer
- [1 mark] To change program flow based on conditions
- [1 mark] To determine which lines of code run next based on condition outcomes
- [Additional] Used for validation, calculation, and processing user choices
2. When should you use CASE instead of IF statements? [2 marks]
Answer
- [1 mark] When comparing multiple values of the SAME variable
- [1 mark] When you have many simple equality checks (menu systems, simple choices)
- [Additional] CASE can make code cleaner for multiple equalities, but IF is more flexible for complex conditions
3. What does "nested IF" mean? [1 mark]
Answer
- [1 mark] An IF statement within another IF statement
- [Additional] "Nested" means stored inside another; used for complex conditional logic
4. What is the purpose of the OTHERWISE clause in CASE? [1 mark]
Answer
- [1 mark] To handle all cases not explicitly listed in the CASE statement
- [Additional] Similar to ELSE in IF statements; provides default/error handling
5. Convert this CASE to IF: CASE OF grade "A": OUTPUT "Excellent" "B": OUTPUT "Good" OTHERWISE: OUTPUT "Try harder" ENDCASE [2 marks]
Answer
- [2 marks]
Section 2: Iteration Constructs
Iteration is repeating a line or block of code using a loop. There are two main types: count-controlled loops (repeat a fixed number of times) and condition-controlled loops (repeat until a condition is met).
What is Iteration?
Iteration can be count-controlled (fixed number of times) or condition-controlled (until condition met).
Count-controlled Loops (FOR)
FOR Loop Syntax
- Loop starts at value1, ends when identifier passes value2
- Increment can be positive or negative
- Identifier updates by increment each iteration
- Use when you know exact number of iterations
Example: Print Numbers 1-5
Nested Count-controlled Loops
Nested FOR loops are used when you need to work with grids, tables, or multi-dimensional data.
1. Outer loop: i = 1
2. Inner loop runs completely: j = 1, 2, 3
3. Output: 1×1=1, 1×2=2, 1×3=3
4. Outer loop: i = 2
5. Inner loop runs completely again
6. Total iterations: 3 × 3 = 9
Condition-controlled Loops
Post-condition (REPEAT-UNTIL)
Checks condition AT THE END, so always runs at least once. Stops when condition becomes TRUE.
Pre-condition (WHILE-DO)
Checks condition AT THE START, so may not execute if false initially. Stops when condition becomes FALSE.
Choosing the Right Loop
| Loop Type | When to Use | Example Scenario |
|---|---|---|
| FOR (Count-controlled) | When you know exact number of iterations in advance | Process 30 student grades, print numbers 1-100 |
| WHILE (Pre-condition) | When you need to check condition before execution; may run 0 times | Read file until EOF, process while valid input |
| REPEAT-UNTIL (Post-condition) | When loop must run at least once; check condition after execution | Input validation, menu systems, password checks |
In exams, justify your choice by explaining: "I chose [loop type] because [reason based on known iterations, need to check at start/end, or need to run at least once]."
Loop Type Simulator
Compare how different loops handle the same task: asking for numbers until 0 is entered.
FOR Loop
Always asks exactly 5 times
WHILE Loop
May stop before 5 if 0 entered
REPEAT-UNTIL
Always asks at least once
Activity 2: Loop Practice
Difficulty: Medium • Time: 15 minutes
Write pseudocode for these scenarios and justify your loop choice:
- Calculate the sum of numbers from 1 to N (user inputs N). Which loop type and why?
- Ask for passwords until correct password "Secret123" is entered. Which loop type and why?
- Process exam marks for exactly 30 students. Which loop type and why?
- Keep asking for test scores until a valid score (0-100) is entered. Which loop type and why?
- Create a multiplication table 1-10 using nested loops.
Solution:
-
INPUT NTotal ← 0FOR i ← 1 TO NTotal ← Total + iNEXT iOUTPUT Total
Justification: FOR loop because we know exact iterations (1 to N).
-
REPEATINPUT "Enter password: ", passwordUNTIL password = "Secret123"OUTPUT "Access granted"
Justification: REPEAT-UNTIL because we need to ask at least once and stop when correct.
-
Total ← 0FOR Student ← 1 TO 30INPUT MarkTotal ← Total + MarkNEXT StudentAverage ← Total / 30OUTPUT Average
Justification: FOR loop because exactly 30 students (known count).
-
REPEATINPUT "Enter score (0-100): ", scoreUNTIL score >= 0 AND score <= 100OUTPUT "Valid score accepted"
Justification: REPEAT-UNTIL because must ask at least once and validate after input.
-
FOR row ← 1 TO 10FOR col ← 1 TO 10OUTPUT row * colNEXT colOUTPUT newlineNEXT row
Note: Nested FOR loops for 10×10 grid (known dimensions).
Check Your Understanding: Iteration
1. What is the difference between count-controlled and condition-controlled loops? [2 marks]
Answer
- [1 mark] Count-controlled: Repeats fixed number of times (FOR loops)
- [1 mark] Condition-controlled: Repeats until condition met (WHILE/REPEAT-UNTIL)
- [Additional] Count-controlled knows iterations in advance; condition-controlled depends on changing conditions
2. When does a WHILE loop stop executing? [1 mark]
Answer
- [1 mark] When the condition becomes FALSE
- [Additional] WHILE continues while condition is TRUE; stops when condition becomes FALSE
3. Why would you choose REPEAT-UNTIL over WHILE? [2 marks]
Answer
- [1 mark] When the loop MUST execute at least once
- [1 mark] When you need to check condition after execution (post-condition)
- [Additional] Example: Input validation (must ask at least once), menu systems
4. How many times does this loop execute? FOR X ← 3 TO 8 [1 mark]
Answer
- [1 mark] 6 times (X = 3, 4, 5, 6, 7, 8)
- [Additional] Formula: (end - start + 1) = (8 - 3 + 1) = 6
5. Convert this FOR loop to WHILE: FOR i ← 1 TO 5 OUTPUT i NEXT i [2 marks]
Answer
- [2 marks]
Key Takeaways
- Selection changes program flow based on conditions using IF or CASE statements
- IF statements can include ELSE for alternative execution and can be nested for complex logic
- CASE statements are useful for comparing multiple values of the same variable
- Iteration/Looping repeats code using FOR (count-controlled), WHILE (pre-condition), or REPEAT-UNTIL (post-condition)
- FOR loops are used when you know the exact number of iterations in advance
- WHILE loops check condition at the start and may not execute at all
- REPEAT-UNTIL loops check condition at the end and always execute at least once
- Justify loop choice by considering: known iterations? check at start or end? must run at least once?
- Nested loops (loop inside loop) are used for grids, tables, and multi-dimensional data
- Always initialize accumulator variables (Total ← 0) before loops
- Ensure loops terminate to avoid infinite loops (make sure condition eventually becomes false)
- Pseudocode conventions: Keywords in uppercase, proper indentation, clear variable names
Question Bank
1. Compare IF and CASE statements. When would you use each? [4 marks]
Answer
- [2 marks] IF statements: More flexible, can handle complex conditions (>, <, AND, OR), nested logic, checking multiple variables
- [2 marks] CASE statements: Cleaner for multiple equality checks on SAME variable, menu systems, simple value matching
- [Example] Use IF for: "if score > 90 AND attendance > 80". Use CASE for: "if day = "Mon" do X, "Tue" do Y"
2. Write pseudocode that takes 10 numbers and outputs their average. [5 marks]
Key points: FOR loop (known count: 10), initialize Total to 0, use Real for Average for decimal accuracy.
3. Identify and fix errors in this pseudocode: [4 marks]
INPUT N
Total = 0
FOR i = 1 TO N
Total = Total + i
ENDFOR
OUTPUT Total
- [1 mark] Variables not declared (should declare N, i, Total)
- [1 mark] Assignment should use ← not = (Total ← 0, Total ← Total + i)
- [1 mark] FOR loop syntax: i ← 1 TO N (not i = 1 TO N)
- [1 mark] Loop should end with NEXT i (not ENDFOR)
4. Write pseudocode using nested loops to output pattern: *
**
***
**** [5 marks]
Explanation: Outer loop controls rows (4 rows). Inner loop prints stars equal to row number (row 1: 1 star, row 2: 2 stars, etc.).
5. Explain why this is an infinite loop and fix it: [3 marks]
X ← 5
WHILE X > 0 DO
OUTPUT X
ENDWHILE
- [1 mark] Infinite because X never changes inside loop
- [1 mark] Condition X > 0 is always true (X always 5)
- [1 mark] Fix: Add X ← X - 1 inside loop to decrement X
6. Write pseudocode for a menu: 1. Add, 2. Subtract, 3. Exit. Use appropriate selection. [4 marks]
Note: CASE is appropriate here because comparing single variable (choice) against multiple constant values.
7. Justify using FOR vs WHILE for: "Process all students in class of 30" [2 marks]
- [1 mark] Use FOR loop because we know exact number of iterations (30 students)
- [1 mark] FOR loop is designed for count-controlled repetition with known start and end
- [Additional] WHILE would require manual counter and is less efficient for this fixed-count scenario
8. Write pseudocode to find largest of 10 numbers. [5 marks]
Key points: FOR loop (9 iterations after first number), first number assumed largest initially, compare and update if larger found.
9. Convert REPEAT-UNTIL to WHILE: REPEAT INPUT X UNTIL X > 10 [2 marks]
Note: REPEAT-UNTIL stops when condition TRUE. WHILE continues while condition TRUE, so need opposite condition (X <= 10 instead of X > 10).
10. Design pseudocode for login system: ask username/password, max 3 attempts. [6 marks]
Key elements: WHILE loop (max 3 attempts), flag variable (LoggedIn), compound condition in WHILE and IF.