📑 Contents

Chapter 11.2: Programming Constructs

Selection and Iteration in CIE Pseudocode

9618 AS Computer Science

📚 Learning Objectives
📌 Prior Knowledge Required
🌟 Did You Know?

Programming constructs are the fundamental building blocks of any algorithm! Every program you write will use a combination of sequence, selection, and iteration. Mastering these three constructs allows you to solve any computational problem!

1. Selection

📖 What is Selection?

Selection is when the flow of a program is changed, depending on a set of conditions. The outcome of this condition will then determine which lines or block of code is run next.

Selection is used for:

📝 Two Types of Selection Statements

1.1 IF Statements

IF statements allow you to execute a set of instructions if a condition is true. The THEN path is followed if the condition is true, and the ELSE path is followed if the condition is false.

START Condition True? YES THEN block NO ELSE block ENDIF IF Statement Flowchart

1.2 IF Statement Syntax

📝 Without ELSE clause
IF <condition> THEN <statement(s)> ENDIF
📝 With ELSE clause
IF <condition> THEN <statement(s)> ELSE <statement(s)> ENDIF

Setting Up Conditions

A condition can be set up in different ways:

Method Example
Using a Boolean variable IF Found THEN PRINT "Success" ELSE PRINT "Not found" ENDIF
Using comparison operators IF Score >= 50 THEN PRINT "Pass" ENDIF
Using logical operators IF (Age >= 18) AND (Age < 70) THEN PRINT "Eligible" ENDIF
Example: Complex Condition
IF ((Height > 1) OR (Weight > 20) OR (Age > 5)) AND (Age < 70)
   THEN PRINT "You can ride"
   ELSE PRINT "Too small, too young or too old"
ENDIF
💡 Exam Tip

Always use proper indentation in your pseudocode! It shows the structure clearly and helps the examiner follow your logic. Remember to always end with ENDIF.

1.3 Nested IF Statements

📖 What are Nested IF Statements?

Nested IF statements are IF statements within IF statements. "Nested" means to be stored inside another. This allows for more complex decision-making.

Example: Game Score Check
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

Example: Validating a Percentage Mark

📝 Pass/Fail Check with Validation
DECLARE Percentage : INTEGER OUTPUT "Enter percentage mark:" INPUT Percentage IF Percentage < 0 OR Percentage > 100 THEN OUTPUT "Invalid percentage - must be 0-100" ELSE IF Percentage >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" ENDIF ENDIF
⚠️ Important Points

1.4 CASE Statements

📖 What is a CASE Statement?

A CASE statement can mean less code but is only useful when comparing multiple values of the same variable. The value of the variable decides which path to take.

📝 CASE Statement Syntax
CASE OF <identifier> <value 1> : <statement(s)> <value 2> : <statement(s)> ... OTHERWISE : <statement(s)> ENDCASE
💡 Exam Tip

The OTHERWISE clause catches all values not explicitly listed. It's like the "else" in IF statements - always include it to handle unexpected inputs!

Example: Direction Input

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
Variable Value 1: "N" Value 2: "S" Value 3: "E" Value 4: "W" OUTPUT "North" OUTPUT "South" OUTPUT "East" OUTPUT "West" OTHERWISE: Invalid ENDCASE CASE Statement Structure

1.5 IF vs CASE: When to Use Each

Feature IF Statement CASE Statement
Flexibility More flexible - can test different variables Less flexible - tests ONE variable only
Conditions Can use complex conditions (AND, OR) Tests specific values only
Best For Range checks, complex logic Menu choices, multiple fixed values
Readability Can become complex with many conditions Cleaner for multiple values of same variable
Default Handling ELSE clause OTHERWISE clause
🧠 Memory Trick

CASE = One Variable, Multiple Values

IF = Any Condition, Any Complexity

Think: CASE is like a menu (one choice from many options), IF is like a decision tree (can branch anywhere!)

❌ Common Mistakes

2. Iteration

📖 What is Iteration?

Iteration is repeating a line or a block of code using a loop. It allows you to execute the same code multiple times without having to write it repeatedly.

2.1 Types of Iteration

📝 Two Categories of Loops
Count-Controlled (FOR Loop) Start Counter = 1 to N Execute Code Next Pre-Condition (WHILE Loop) Condition True? Execute Code Loop Post-Condition (REPEAT Loop) Execute Code Condition True? No

2.2 Count-Controlled Loops (FOR)

📖 What is a FOR Loop?

A FOR loop is a count-controlled loop where the code is repeated a fixed number of times. The loop starts at a value and counts to another value, executing the code block each time.

📝 FOR Loop Syntax
FOR <identifier> ← <value1> TO <value2> <statements(s)> NEXT <identifier>
📝 FOR Loop with STEP
FOR <identifier> ← <value1> TO <value2> STEP <increment> <statements(s)> NEXT <identifier>
⚠️ Important Points

Example: Print Numbers 1 to 5

FOR i ← 1 TO 5 OUTPUT i NEXT i // Output: 1 2 3 4 5

Example: Count Down (Negative Step)

FOR i ← 10 TO 1 STEP -1 OUTPUT i NEXT i // Output: 10 9 8 7 6 5 4 3 2 1

2.3 Nested FOR Loops

📖 What are Nested Loops?

Nested loops are loops inside loops. The outer loop runs, and for each iteration, the inner loop runs completely.

Example: Multiplication Table
FOR i ← 1 TO 3
   FOR j ← 1 TO 3
      OUTPUT i, " x ", j, " = ", i * j
   NEXT j
NEXT i

Output:
1 x 1 = 1, 1 x 2 = 2, 1 x 3 = 3
2 x 1 = 2, 2 x 2 = 4, 2 x 3 = 6
3 x 1 = 3, 3 x 2 = 6, 3 x 3 = 9
FOR i ← 1 TO 3 (Outer Loop) FOR j ← 1 TO 3 (i = 1) 1x1=1 1x2=2 1x3=3 FOR j ← 1 TO 3 (i = 2) 2x1=2 2x2=4 2x3=6 FOR j ← 1 TO 3 (i = 3) 3x1=3 3x2=6 3x3=9
💡 Exam Tip

In nested loops, the inner loop completes ALL iterations before the outer loop moves to its next iteration. Total iterations = outer iterations × inner iterations.

2.4 Pre-Condition Loops (WHILE)

📖 What is a WHILE Loop?

A WHILE loop is a pre-condition loop. The condition is tested BEFORE the statements are executed. If the condition is FALSE initially, the loop body will never execute (it may run 0 or more times).

📝 WHILE Loop Syntax
WHILE <condition> DO <statement(s)> ENDWHILE
⚠️ Key Points

Example: Password Check

DECLARE Password : STRING Password ← "" WHILE Password <> "admin" DO OUTPUT "Enter the password:" INPUT Password IF Password <> "admin" THEN OUTPUT "Incorrect, try again." ENDIF ENDWHILE OUTPUT "Access granted!"
💡 When to Use WHILE

Use WHILE when you want to check the condition before running the loop. Perfect for validation where the loop might not need to run at all (e.g., if password is already correct).

2.5 Post-Condition Loops (REPEAT...UNTIL)

📖 What is a REPEAT...UNTIL Loop?

A REPEAT...UNTIL loop is a post-condition loop. The statements are executed BEFORE the condition is tested. The loop will always execute at least once.

📝 REPEAT...UNTIL Syntax
REPEAT <statement(s)> UNTIL <condition>
⚠️ Key Points

Example: Valid Input

DECLARE Age : INTEGER REPEAT OUTPUT "Enter your age (1-120):" INPUT Age IF Age < 1 OR Age > 120 THEN OUTPUT "Invalid age. Please try again." ENDIF UNTIL Age >= 1 AND Age <= 120 OUTPUT "Age accepted:", Age
WHILE (Pre-condition) Test First True? FALSE → Skip TRUE → Run Execute Code REPEAT (Post-condition) Execute Code Run First! Test After True? TRUE → Stop FALSE → Loop

2.6 Choosing the Right Loop

Loop Type When to Use Example Scenario
FOR
(Count-controlled)
When you know in advance how many times the loop should run Repeating an action 5 times; generating a multiplication table; processing an array of known size
WHILE
(Pre-condition)
When you want to check condition before running; may run 0 or more times Keep asking for a valid password before granting access; processing data that might be empty
REPEAT...UNTIL
(Post-condition)
When you want the loop to run at least once; stop when condition becomes true Ask the user for input and validate it after first run; menu systems
🧠 Memory Trick: Loop Selection
❌ Common Mistakes with Loops
💡 Exam Tip

Remember: WHILE condition is for continuing the loop, REPEAT...UNTIL condition is for stopping the loop!

WHILE: Continue while TRUE → Stop when FALSE

REPEAT: Continue while FALSE → Stop when TRUE

3. Exam-Style Questions

1. Write pseudocode for an algorithm that asks the user to enter a number. If the number is positive, output "Positive". If the number is negative, output "Negative". If the number is zero, output "Zero". [4 marks]

Answer:

DECLARE Number : INTEGER OUTPUT "Enter a number:" INPUT Number IF Number > 0 THEN OUTPUT "Positive" ELSE IF Number < 0 THEN OUTPUT "Negative" ELSE OUTPUT "Zero" ENDIF ENDIF

Alternative using nested IF structure correctly:

  • Correct use of IF...THEN...ELSE structure
  • Proper nesting with ENDIF
  • Correct condition for positive (> 0)
  • Correct condition for negative (< 0)
  • Handles zero case appropriately
2. Write pseudocode using a CASE statement that outputs the day name when the user enters a number from 1 to 7. Include error handling for invalid inputs. [5 marks]

Answer:

DECLARE DayNum : INTEGER OUTPUT "Enter a day number (1-7):" INPUT DayNum CASE OF DayNum 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
  • Correct CASE...OF syntax
  • All 7 days correctly mapped
  • OTHERWISE clause for error handling
  • ENDCASE used to close statement
  • Proper variable declaration and input
3. Explain the difference between a WHILE loop and a REPEAT...UNTIL loop. Give an example of when you would use each. [6 marks]

Answer:

  • WHILE: Pre-condition loop - tests condition BEFORE executing the loop body. May execute 0 or more times.
  • REPEAT...UNTIL: Post-condition loop - tests condition AFTER executing the loop body. Always executes at least once.
  • WHILE continues while condition is TRUE; stops when FALSE
  • REPEAT continues while condition is FALSE; stops when TRUE
  • WHILE example: Checking password before allowing access - might not need to run if password is already correct
  • REPEAT example: Validating user input - always need to ask at least once before checking validity
  • Additional point: WHILE is safer when you don't want code to run if data is invalid initially
4. Write pseudocode that uses a FOR loop to calculate and output the sum of all numbers from 1 to 100. [4 marks]

Answer:

DECLARE Total : INTEGER DECLARE i : INTEGER Total ← 0 FOR i ← 1 TO 100 Total ← Total + i NEXT i OUTPUT "The sum is: ", Total
  • Correct variable declarations
  • Initialisation of Total to 0
  • Correct FOR loop syntax (1 TO 100)
  • Accumulator pattern (Total ← Total + i)
  • NEXT i to close the loop
  • Output the final result
5. Write pseudocode for a nested loop that prints a 5x5 grid of asterisks (*). [5 marks]

Answer:

DECLARE Row : INTEGER DECLARE Col : INTEGER FOR Row ← 1 TO 5 FOR Col ← 1 TO 5 OUTPUT "*" // Without newline NEXT Col OUTPUT "" // New line after each row NEXT Row

Alternative with inline output:

FOR Row ← 1 TO 5 OUTPUT "*****" NEXT Row
  • Correct nested FOR loop structure
  • Outer loop for rows (1 TO 5)
  • Inner loop for columns (1 TO 5)
  • Output asterisk character
  • NEXT statements for both loops
  • Additional points: Shows understanding of nested iteration

3. Exam-Style Questions (Continued)

6. Write pseudocode that repeatedly asks the user to enter a positive number. The program should keep asking until a positive number is entered, then output "Thank you" with the number. Use a REPEAT...UNTIL loop. [5 marks]

Answer:

DECLARE Number : INTEGER REPEAT OUTPUT "Enter a positive number:" INPUT Number IF Number <= 0 THEN OUTPUT "Not positive. Try again." ENDIF UNTIL Number > 0 OUTPUT "Thank you. You entered: ", Number
  • Correct REPEAT...UNTIL syntax
  • Input statement inside the loop
  • Error message for non-positive input
  • Correct UNTIL condition (Number > 0)
  • Final output after loop exits
  • Additional: Shows understanding that REPEAT runs at least once
7. Explain why you would use a CASE statement instead of multiple IF statements. Give an example to illustrate your answer. [4 marks]

Answer:

  • CASE statements are more readable when comparing multiple values of the same variable
  • CASE statements result in cleaner, shorter code for multi-way selection
  • IF statements are more flexible but can become complex with many conditions
  • Example: Menu selection with options 1-4 - using CASE is clearer than IF...ELSE IF...ELSE IF...
  • Additional: CASE can only test equality, not ranges or complex conditions
8. Write pseudocode for a program that uses a WHILE loop to allow a user to guess a secret number (assume secret number is 42). The program should output "Too high", "Too low", or "Correct!" after each guess, and stop when the correct number is guessed. [6 marks]

Answer:

DECLARE Secret : INTEGER DECLARE Guess : INTEGER Secret ← 42 Guess ← 0 WHILE Guess <> Secret DO OUTPUT "Guess the secret number:" INPUT Guess IF Guess > Secret THEN OUTPUT "Too high" ELSE IF Guess < Secret THEN OUTPUT "Too low" ELSE OUTPUT "Correct!" ENDIF ENDIF ENDWHILE
  • Variable declarations and initialisation
  • Secret number assigned (42)
  • WHILE loop with correct condition (Guess ≠ Secret)
  • Input inside the loop
  • Nested IF for comparison (too high/too low/correct)
  • ENDWHILE to close the loop
  • Additional: Good structure showing WHILE usage for unknown iterations
9. Write pseudocode that uses a FOR loop with STEP to output all even numbers from 2 to 20. [3 marks]

Answer:

DECLARE i : INTEGER FOR i ← 2 TO 20 STEP 2 OUTPUT i NEXT i
  • Correct FOR loop syntax with STEP
  • Starting value of 2
  • Ending value of 20
  • STEP value of 2 for even numbers
  • NEXT i to close loop
  • Additional: Shows understanding of STEP keyword
10. A program needs to validate a user's age. The age must be between 18 and 65 inclusive. Write pseudocode that uses appropriate selection and iteration to repeatedly ask for age until a valid age is entered. Include clear feedback for invalid inputs. [6 marks]

Answer:

DECLARE Age : INTEGER REPEAT OUTPUT "Enter your age (18-65):" INPUT Age IF Age < 18 THEN OUTPUT "Too young. Must be 18 or older." ELSE IF Age > 65 THEN OUTPUT "Too old. Must be 65 or younger." ENDIF ENDIF UNTIL Age >= 18 AND Age <= 65 OUTPUT "Valid age accepted:", Age
  • REPEAT...UNTIL used appropriately (run at least once)
  • Input statement inside loop
  • Nested IF to check both conditions
  • Clear error messages for each invalid case
  • Correct UNTIL condition (Age >= 18 AND Age <= 65)
  • Final confirmation output
  • Additional: Demonstrates selection AND iteration together

4. Glossary

Term Definition
Selection A programming construct where the flow of execution is changed based on a condition being true or false
Iteration A programming construct that repeats a block of code multiple times; also called a loop
IF Statement A selection statement that executes code if a condition is true; may include ELSE for alternative code
CASE Statement A selection statement that compares a single variable against multiple values and executes matching code
FOR Loop A count-controlled loop that repeats code a fixed number of times
WHILE Loop A pre-condition loop that continues while a condition is true; may execute 0 times
REPEAT...UNTIL A post-condition loop that executes at least once and stops when condition becomes true
Nested When one construct is placed inside another, such as an IF inside another IF or a loop inside a loop
Count-controlled A type of loop where the number of iterations is known before the loop starts
Condition-controlled A type of loop where iterations continue until a condition is met
Pre-condition A loop where the condition is tested before the loop body executes (WHILE)
Post-condition A loop where the condition is tested after the loop body executes (REPEAT...UNTIL)
Infinite Loop A loop that never terminates because the exit condition is never met
ENDIF Keyword that marks the end of an IF statement in pseudocode
ENDCASE Keyword that marks the end of a CASE statement in pseudocode
ENDWHILE Keyword that marks the end of a WHILE loop in pseudocode
OTHERWISE The default case in a CASE statement, executed when no other values match
STEP Keyword in FOR loop to specify the increment value between iterations

5. Exam Success Tips

💡 Selection Statements
💡 CASE Statements
💡 FOR Loops
💡 WHILE vs REPEAT

5. Exam Success Tips (Continued)

❌ Common Mistakes to Avoid
🧠 Quick Memory Aids
⚠️ Exam Day Reminders

6. Key Takeaways

📌 Selection Summary
📌 Iteration Summary
📌 Choosing the Right Construct
Situation Best Construct
Compare one variable to multiple fixed values CASE statement
Complex conditions, range checks, or multiple variables IF statement
Known number of repetitions FOR loop
Unknown repetitions, might not need to run at all WHILE loop
Unknown repetitions, must run at least once REPEAT...UNTIL loop
🌟 Final Thought

Every algorithm can be built using just three structures: Sequence (one step after another), Selection (choosing between paths), and Iteration (repeating code). Master these constructs and you can solve any programming problem!