S/I

11.2 Constructs

Understanding selection constructs (IF, CASE) and iteration constructs (FOR, WHILE, REPEAT) in pseudocode

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

// Without ELSE clause
IF <condition> THEN
<statement(s)>
ENDIF
// With ELSE clause
IF <condition> THEN
<statement(s)>
ELSE
<statement(s)>
ENDIF
Remember:

Conditions must evaluate to TRUE or FALSE. Use comparison operators: =, <, >, <=, >=, <> (not equal).

Example: Weather Check

weather = input("What is the weather like today? (sunny, rainy, snowy): ")
IF weather = "sunny" THEN
OUTPUT "Don't forget your sunglasses!"
ELSEIF weather = "rainy" THEN
OUTPUT "Take an umbrella with you."
ELSEIF weather = "snowy" THEN
OUTPUT "Wear warm clothes!"
ELSE
OUTPUT "Not sure what to suggest for that kind of weather."
ENDIF
weather
sunny
Output
Don't forget...

Nested IF Statements

Nested IF statements are an IF statement within another IF statement. "Nested" means to be 'stored inside the other'.

// Example from PDF: Game scoring system
IF Player2Score > Player1Score THEN
IF Player2Score > HighScore THEN
OUTPUT Player2, " is champion and highest scorer"
ELSE
OUTPUT Player2, " is the new champion"
ENDIF
ELSE
OUTPUT Player1, " is still the champion"
IF Player1Score > HighScore THEN
OUTPUT Player1, " is also the highest scorer"
ENDIF
ENDIF
Flow Explanation:

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:
// Comparison: 92 > 85 = TRUE
// Comparison: 92 > 95 = FALSE
Player2 is the new champion
Start
Player2 > Player1?
Player2 > HighScore?
Output result

CASE Statements

CASE Statement Structure

CASE OF <identifier>
<value 1> : <statement1>
<statement2>
...
<value 2> : <statement1>
<statement2>
...
OTHERWISE: <statement1>
<statement2>
ENDCASE
When to use CASE:

Use when comparing multiple values of the SAME variable. IF statements are more flexible for complex conditions.

Example: Direction Check

DECLARE Direction : STRING
OUTPUT "Enter a direction (N, S, E, W):"
INPUT Direction
CASE OF Direction
"N" : OUTPUT "You are heading North"
"S" : OUTPUT "You are heading South"
"E" : OUTPUT "You are heading East"
"W" : OUTPUT "You are heading West"
OTHERWISE: OUTPUT "Invalid direction entered"
ENDCASE
Output: You are heading North

Activity 1: Selection Practice

Difficulty: Easy • Time: 10 minutes

Write pseudocode for these scenarios:

  1. Write pseudocode that checks if a number is positive, negative, or zero using IF statements.
  2. Convert the weather example from IF to CASE statement.
  3. Write pseudocode for a simple calculator that takes two numbers and an operator (+, -, *, /) and performs the calculation using CASE.
  4. Write nested IF statements to determine a student's grade: A (≥90), B (80-89), C (70-79), D (60-69), F (<60).
Solution:
  1. INPUT number
    IF number > 0 THEN
    OUTPUT "Positive"
    ELSEIF number < 0 THEN
    OUTPUT "Negative"
    ELSE
    OUTPUT "Zero"
    ENDIF
  2. 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
  3. INPUT num1, num2, operator
    CASE OF operator
    "+" : OUTPUT num1 + num2
    "-" : OUTPUT num1 - num2
    "*" : OUTPUT num1 * num2
    "/" : OUTPUT num1 / num2
    OTHERWISE: OUTPUT "Invalid operator"
    ENDCASE
  4. INPUT score
    IF score >= 90 THEN
    OUTPUT "A"
    ELSEIF score >= 80 THEN
    OUTPUT "B"
    ELSEIF score >= 70 THEN
    OUTPUT "C"
    ELSEIF score >= 60 THEN
    OUTPUT "D"
    ELSE
    OUTPUT "F"
    ENDIF

Check Your Understanding: Selection

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
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
Answer
  • [1 mark] An IF statement within another IF statement
  • [Additional] "Nested" means stored inside another; used for complex conditional logic
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
Answer
  • [2 marks]
  • IF grade = "A" THEN
    OUTPUT "Excellent"
    ELSEIF grade = "B" THEN
    OUTPUT "Good"
    ELSE
    OUTPUT "Try harder"
    ENDIF

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

// Basic FOR loop
FOR <identifier> ← <value1> TO <value2>
<statement(s)>
NEXT <identifier>
// With STEP increment
FOR <identifier> ← <value1> TO <value2> STEP <increment>
<statement(s)>
NEXT <identifier>
Key Points:
  • 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

// Print numbers 1 to 5
FOR i ← 1 TO 5
OUTPUT i
NEXT i
// Output: 1, 2, 3, 4, 5
Current i
1
Output
1

Nested Count-controlled Loops

Nested FOR loops are used when you need to work with grids, tables, or multi-dimensional data.

// Multiplication table 1-3
FOR i ← 1 TO 3
FOR j ← 1 TO 3
OUTPUT i, " x ", j, " = ", i * j
NEXT j
NEXT i
How it works:

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)

// Always executes at least once
REPEAT
<statement(s)>
UNTIL <condition>
// Example: Password check
REPEAT
INPUT "Enter password: ", password
UNTIL password = "admin"
OUTPUT "Access granted!"
Key Feature:

Checks condition AT THE END, so always runs at least once. Stops when condition becomes TRUE.

Pre-condition (WHILE-DO)

// May not execute at all
WHILE <condition> DO
<statement(s)>
ENDWHILE
// Example: Sum while positive
Total ← 0
INPUT num
WHILE num > 0 DO
Total ← Total + num
INPUT num
ENDWHILE
OUTPUT Total
Key Feature:

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
Justification Tip:

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
Total ← 0
FOR i ← 1 TO 5
INPUT num
Total ← Total + num
NEXT i
OUTPUT Total

Always asks exactly 5 times

WHILE Loop
Total ← 0
INPUT num
WHILE num ≠ 0 DO
Total ← Total + num
INPUT num
ENDWHILE
OUTPUT Total

May stop before 5 if 0 entered

REPEAT-UNTIL
Total ← 0
REPEAT
INPUT num
Total ← Total + num
UNTIL num = 0
OUTPUT Total

Always asks at least once

Loop Type
FOR
Total
0
Iterations
0
Current Input
-

Activity 2: Loop Practice

Difficulty: Medium • Time: 15 minutes

Write pseudocode for these scenarios and justify your loop choice:

  1. Calculate the sum of numbers from 1 to N (user inputs N). Which loop type and why?
  2. Ask for passwords until correct password "Secret123" is entered. Which loop type and why?
  3. Process exam marks for exactly 30 students. Which loop type and why?
  4. Keep asking for test scores until a valid score (0-100) is entered. Which loop type and why?
  5. Create a multiplication table 1-10 using nested loops.
Solution:
  1. INPUT N
    Total ← 0
    FOR i ← 1 TO N
    Total ← Total + i
    NEXT i
    OUTPUT Total

    Justification: FOR loop because we know exact iterations (1 to N).

  2. REPEAT
    INPUT "Enter password: ", password
    UNTIL password = "Secret123"
    OUTPUT "Access granted"

    Justification: REPEAT-UNTIL because we need to ask at least once and stop when correct.

  3. Total ← 0
    FOR Student ← 1 TO 30
    INPUT Mark
    Total ← Total + Mark
    NEXT Student
    Average ← Total / 30
    OUTPUT Average

    Justification: FOR loop because exactly 30 students (known count).

  4. REPEAT
    INPUT "Enter score (0-100): ", score
    UNTIL score >= 0 AND score <= 100
    OUTPUT "Valid score accepted"

    Justification: REPEAT-UNTIL because must ask at least once and validate after input.

  5. FOR row ← 1 TO 10
    FOR col ← 1 TO 10
    OUTPUT row * col
    NEXT col
    OUTPUT newline
    NEXT row

    Note: Nested FOR loops for 10×10 grid (known dimensions).

Check Your Understanding: Iteration

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
Answer
  • [1 mark] When the condition becomes FALSE
  • [Additional] WHILE continues while condition is TRUE; stops when condition becomes FALSE
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
Answer
  • [1 mark] 6 times (X = 3, 4, 5, 6, 7, 8)
  • [Additional] Formula: (end - start + 1) = (8 - 3 + 1) = 6
Answer
  • [2 marks]
  • i ← 1
    WHILE i <= 5 DO
    OUTPUT i
    i ← i + 1
    ENDWHILE

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

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"
DECLARE Total, Count, Num : Integer
DECLARE Average : Real
Total ← 0
FOR Count ← 1 TO 10
INPUT "Enter number: ", Num
Total ← Total + Num
NEXT Count
Average ← Total / 10
OUTPUT "Average is: ", Average

Key points: FOR loop (known count: 10), initialize Total to 0, use Real for Average for decimal accuracy.

  • [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)
DECLARE N, i, Total : Integer
INPUT N
Total ← 0
FOR i ← 1 TO N
Total ← Total + i
NEXT i
OUTPUT Total
DECLARE row, stars : Integer
FOR row ← 1 TO 4
FOR stars ← 1 TO row
OUTPUT "*"
NEXT stars
OUTPUT newline
NEXT row

Explanation: Outer loop controls rows (4 rows). Inner loop prints stars equal to row number (row 1: 1 star, row 2: 2 stars, etc.).

  • [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
X ← 5
WHILE X > 0 DO
OUTPUT X
X ← X - 1
ENDWHILE
DECLARE choice : Integer
DECLARE num1, num2, result : Real
OUTPUT "1. Add, 2. Subtract, 3. Exit"
INPUT choice
CASE OF choice
1 : INPUT num1, num2
   result ← num1 + num2
   OUTPUT result
2 : INPUT num1, num2
   result ← num1 - num2
   OUTPUT result
3 : OUTPUT "Goodbye"
OTHERWISE: OUTPUT "Invalid choice"
ENDCASE

Note: CASE is appropriate here because comparing single variable (choice) against multiple constant values.

  • [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
DECLARE Largest, Num, Count : Integer
INPUT "Enter first number: ", Largest
FOR Count ← 1 TO 9
INPUT "Enter next number: ", Num
IF Num > Largest THEN
Largest ← Num
ENDIF
NEXT Count
OUTPUT "Largest is: ", Largest

Key points: FOR loop (9 iterations after first number), first number assumed largest initially, compare and update if larger found.

INPUT X
WHILE X <= 10 DO
INPUT X
ENDWHILE

Note: REPEAT-UNTIL stops when condition TRUE. WHILE continues while condition TRUE, so need opposite condition (X <= 10 instead of X > 10).

DECLARE Username, Password : STRING
DECLARE Attempts : INTEGER
Attempts ← 0
LoggedIn ← FALSE
WHILE Attempts < 3 AND LoggedIn = FALSE DO
INPUT "Username: ", Username
INPUT "Password: ", Password
IF Username = "admin" AND Password = "secret" THEN
LoggedIn ← TRUE
OUTPUT "Login successful"
ELSE
OUTPUT "Invalid credentials"
Attempts ← Attempts + 1
ENDIF
ENDWHILE
IF LoggedIn = FALSE THEN
OUTPUT "Maximum attempts reached"
ENDIF

Key elements: WHILE loop (max 3 attempts), flag variable (LoggedIn), compound condition in WHILE and IF.