Learning Objectives
By the end of this lesson, you will be able to:
- Write pseudocode using basic iteration constructs
- Document simple algorithms using pseudocode
- Understand and implement FOR-TO-NEXT loops for counting-based repetition
- Use WHILE-DO-ENDWHILE and REPEAT-UNTIL loops for condition-based repetition
- Differentiate between pre-condition and post-condition loops
- Implement nested loops for complex repetition patterns
- Apply looping constructs to solve real-world problems like calculating averages and finding maximum values
Key Terms
Looping/Repetition
A way to repeat certain instructions either a set number of times or depending on a condition
FOR-TO-NEXT Loop
Counting-based loop where a variable goes from start to end value, incrementing by one each time
WHILE-DO-ENDWHILE
Pre-condition loop that repeats while a condition is true, checking at the start
REPEAT-UNTIL
Post-condition loop that repeats until a condition becomes true, checking at the end
Iteration
Statements in an algorithm that need repeating; one complete cycle of a loop
Conditional Loop
A loop that repeats based on a condition rather than a fixed count
Unconditional Loop
A loop where the number of repetitions is set at the beginning (like FOR loop)
Nested Loops
A loop inside another loop; each time through the outer loop, the inner loop completes fully
Counter Variable
A variable used to keep track of how many times a loop has executed
Pre-Condition Loop
Loop that checks condition at the beginning (WHILE-DO-ENDWHILE)
Post-Condition Loop
Loop that checks condition at the end (REPEAT-UNTIL)
Running Total
A cumulative sum that gets updated each time through a loop
Introduction to Looping
Looping or repetition is a way to repeat certain instructions either a set number of times or depending upon a particular condition. When some statements of an algorithm need repeating, these statements are called iteration.
Two Main Loop Constructs
1. FOR-TO-NEXT Loop
Used for counting-based looping. A variable is set up with a start value and an end value, then incremented in steps of one until the end value is reached.
2. WHILE & REPEAT-UNTIL
Used for condition-based looping. These repeat based on whether a condition is true or false.
FOR loops are unconditional - you know exactly how many times they'll run. WHILE and REPEAT loops are conditional - they run until a condition changes.
Basic FOR Loop Example
This loop runs 5 times. X starts at 1, increases to 2, 3, 4, and finally 5. Each time, it calculates X*3 and outputs the result.
Real-Life Example: School Attendance System
Think of a school attendance system that needs to record attendance for all 30 students in a class:
Without Loops
With FOR Loop
Loops make code shorter, easier to read, and easier to maintain. If the class size changes to 35, you only change one number instead of adding 5 more lines!
FOR Loop Visualizer
See how a FOR loop works step by step. The loop counter (X) increases each time until it reaches the end value.
How it works: The FOR loop sets up a counter variable (X) that starts at the beginning value. Each time through the loop:
- Execute the loop body (calculate Answer = X * 3)
- Output the result
- Increment X by the step value
- Check if X has passed the end value
- If not, repeat from step 1
Check Your Understanding: Introduction to Loops
1. What is the main purpose of using loops in algorithms? [2 marks]
Answer
- [1 mark] To repeat certain instructions either a set number of times or depending on a condition
- [1 mark] To make algorithms shorter, more readable, and easier to maintain by avoiding repetitive code
- [Additional] Loops allow processing of multiple data items with the same code, like handling all students in a class
2. What is the difference between FOR loops and WHILE/REPEAT loops? [2 marks]
Answer
- [1 mark] FOR loops are counting-based loops used when you know exactly how many times to repeat
- [1 mark] WHILE and REPEAT loops are condition-based loops used when repetition depends on a condition that may change
- [Additional] FOR loops are unconditional (fixed count), WHILE/REPEAT are conditional (run until condition changes)
3. How many times will this loop execute? FOR X = 3 TO 8 [1 mark]
Answer
- [1 mark] 6 times (when X = 3, 4, 5, 6, 7, 8)
- [Additional] The formula is: (end - start + 1) = (8 - 3 + 1) = 6 iterations
4. What is meant by "iteration" in the context of loops? [1 mark]
Answer
- [1 mark] Iteration refers to statements in an algorithm that need repeating, or one complete cycle of a loop
- [Additional] Each time a loop executes its body completely is called one iteration
5. Why are FOR loops considered "unconditional"? [2 marks]
Answer
- [1 mark] Because the number of repetitions is set at the beginning when the loop starts
- [1 mark] The loop will always run exactly the specified number of times regardless of any conditions during execution
- [Additional] Unlike WHILE loops which might stop early if a condition becomes false, FOR loops complete their full count
FOR-TO-NEXT Loop Applications
FOR loops are ideal when you know exactly how many times you need to repeat something. Common applications include calculating averages, finding maximum/minimum values, and processing fixed-size data sets.
Example 1: Calculating Average of N Numbers
Pseudocode
- Ask for number of values
- Loop that number of times
- Enter a value in loop
- Add the value to Total in loop
- Calculate and output average
Fixed Count Example (15 numbers)
This loop will always run exactly 15 times, asking for 15 numbers, summing them, then calculating the average.
Example 2: Finding the Largest Number
Pseudocode
How It Works
Step-by-Step Execution
We need 10 numbers total. First number is read outside the loop and assumed to be the biggest. Then we loop 9 more times.
Inside the Loop
For each new number: compare with BiggestSoFar. If new number is bigger, update BiggestSoFar. Otherwise, keep current BiggestSoFar.
Why FOR loop works here
We know exactly how many numbers: 10 total. First one outside loop + 9 inside loop = 10 numbers.
Numbers: 5, 12, 3, 7, 12, 9, 15, 4, 8, 11
BiggestSoFar: 5 → 12 → 15 (final answer)
Real-Life Example: Exam Score Analysis
A teacher needs to analyze exam scores for a class of 25 students:
This single FOR loop calculates both the class average AND finds the highest score efficiently. Without loops, the teacher would need 25 lines for input, 25 lines for adding to total, and 24 comparisons!
Activity 1: FOR Loop Practice
Write pseudocode solutions for these problems using FOR loops:
- Write pseudocode that takes 20 numbers as input and calculates their sum.
- Write pseudocode that takes 8 numbers as input and outputs the smallest number.
- Write pseudocode to calculate the factorial of a number N (N! = 1 × 2 × 3 × ... × N).
- Write pseudocode that outputs the first 10 multiples of 7 (7, 14, 21, ..., 70).
- Write pseudocode that takes 5 test scores as input and outputs whether each score is above or below the class average of 65.
Solution:
-
Sum of 20 numbers:
Total ← 0FOR Count ← 1 TO 20INPUT "Enter number: ", NumTotal ← Total + NumNEXTOUTPUT "Sum of 20 numbers is: ", Total -
Smallest of 8 numbers:
INPUT "Enter first number: ", SmallestFOR Count ← 1 TO 7INPUT "Enter next number: ", NumIF Num < Smallest THENSmallest ← NumENDIFNEXTOUTPUT "Smallest number is: ", Smallest -
Factorial of N:
INPUT "Enter number N: ", NFactorial ← 1FOR Count ← 1 TO NFactorial ← Factorial × CountNEXTOUTPUT N, "! = ", Factorial -
First 10 multiples of 7:
FOR Count ← 1 TO 10Multiple ← Count × 7OUTPUT MultipleNEXT -
Scores above/below average:
Average ← 65FOR Count ← 1 TO 5INPUT "Enter test score: ", ScoreIF Score ≥ Average THENOUTPUT "Score ", Score, " is above or equal to average"ELSEOUTPUT "Score ", Score, " is below average"ENDIFNEXT
Check Your Understanding: FOR Loops
1. In the average calculation pseudocode, why is the first number read outside the loop in the "find largest" example? [2 marks]
Answer
- [1 mark] We need an initial value for BiggestSoFar to compare with other numbers
- [1 mark] Reading it outside allows the loop to run exactly 9 times for the remaining 9 numbers (10 total)
- [Additional] If we read all 10 inside the loop, we'd need to handle the first comparison differently or use a very small initial value
2. What would happen if we forgot to initialize Total to 0 in the average calculation? [2 marks]
Answer
- [1 mark] Total would contain an unknown/garbage value from memory
- [1 mark] The final sum and average would be incorrect because we'd be adding numbers to an unknown starting value
- [Additional] Always initialize accumulator variables (like Total) to 0 before using them in a loop
3. How would you modify the average calculation to work for any number of values instead of fixed 15? [2 marks]
Answer
- [1 mark] Ask the user how many values they want to average: INPUT "How many numbers?", N
- [1 mark] Change the FOR loop to: FOR Count ← 1 TO N
- [Additional] Also change the average calculation to: Average ← Total / N
4. What is the purpose of the Counter variable in a FOR loop? [1 mark]
Answer
- [1 mark] To keep track of how many times the loop has executed and control when the loop should stop
- [Additional] The Counter starts at the beginning value, increments each iteration, and the loop stops when it passes the end value
5. Write a FOR loop that outputs even numbers from 2 to 20. [2 marks]
Answer
- [2 marks]
- [Alternative] Could also use: FOR Count ← 1 TO 10 then output Count×2
REPEAT-UNTIL Loops
REPEAT-UNTIL is a post-condition loop used when the number of repetitions is not known in advance. Actions are repeated UNTIL a given condition becomes true. Actions in this loop are always completed at least once because the condition is checked at the end.
Basic REPEAT-UNTIL Structure
Loop executes AT LEAST ONCE because condition is checked at the end, not the beginning.
Example: Sum Until Zero
This loop keeps asking for numbers and adding them until the user enters 0. The 0 is added to the total (making no change), then the loop stops.
Important: REPEAT-UNTIL vs Other Loops
Students often confuse when to use REPEAT-UNTIL versus WHILE or FOR loops. Here's a clear guide:
Use REPEAT-UNTIL when:
- Loop must run at least once - condition checked at end
- Don't know exact iterations - depends on user/data
- Stop when condition becomes TRUE - "until" means stop when true
- Example: Menu systems, input validation, games
Use WHILE when:
- Loop might not run at all - condition checked at start
- Stop when condition becomes FALSE - "while" means continue while true
- Example: Reading data until EOF, processing while valid
Use FOR when:
- Know exact number of iterations - fixed count
- Processing arrays/lists - known size
- Example: Grades for 30 students, days in month
Key Insight: REPEAT-UNTIL Logic
REPEAT-UNTIL is like saying: "Do this task, then check if we're done. If not, do it again." This guarantees the task happens at least once. WHILE is like: "Check if we should do this task. If yes, do it, then check again."
Remember: UNTIL condition means "keep repeating UNTIL this becomes true." The loop stops when the condition is TRUE.
REPEAT-UNTIL Examples
Finding Largest with REPEAT-UNTIL
This does the same as the FOR loop example but with REPEAT-UNTIL. We need a Counter variable to track how many numbers we've processed.
Finding Largest Until Zero
This version stops when 0 is entered. The 0 is included in the comparison but won't be largest (unless all numbers are negative and 0 is largest!).
REPEAT-UNTIL Loop Simulator
Simulate a REPEAT-UNTIL loop that continues until a specific condition is met. Enter numbers below and see how the loop behaves.
Numbers Entered:
How REPEAT-UNTIL works:
- Execute the loop body (input number, add to total)
- Check the condition: is num = 0?
- If condition is TRUE: exit the loop
- If condition is FALSE: go back to step 1 and repeat
- The loop always runs at least once because condition is checked AFTER the body
Activity 2: REPEAT-UNTIL Practice
Write pseudocode solutions using REPEAT-UNTIL loops:
- Write pseudocode that asks for passwords until the correct password "Secret123" is entered.
- Write pseudocode that takes numbers as input and counts how many are entered until a negative number is input.
- Write pseudocode for a simple calculator that repeatedly asks for two numbers and an operation (+, -, *, /) until the user enters 'Q' for quit.
- Write pseudocode that keeps asking for test scores (0-100) until a valid score is entered (valid means between 0 and 100 inclusive).
- Convert the FOR loop example for finding largest of 10 numbers to use REPEAT-UNTIL instead.
Solution:
-
Password check:
DECLARE password : StringREPEATINPUT "Enter password: ", passwordUNTIL password = "Secret123"OUTPUT "Access granted" -
Count numbers until negative:
DECLARE num, count : Integercount ← 0REPEATINPUT "Enter a number: ", numcount ← count + 1UNTIL num < 0OUTPUT "Total numbers entered: ", count - 1 -
Simple calculator:
DECLARE num1, num2, result : RealDECLARE op : CharREPEATINPUT "Enter first number: ", num1INPUT "Enter second number: ", num2INPUT "Enter operation (+, -, *, /) or Q to quit: ", opIF op = '+' THEN result ← num1 + num2ELSEIF op = '-' THEN result ← num1 - num2ELSEIF op = '*' THEN result ← num1 * num2ELSEIF op = '/' THEN result ← num1 / num2ENDIFOUTPUT "Result: ", resultUNTIL op = 'Q' -
Input validation:
DECLARE score : IntegerREPEATINPUT "Enter test score (0-100): ", scoreUNTIL score ≥ 0 AND score ≤ 100OUTPUT "Valid score accepted: ", score -
Convert FOR to REPEAT-UNTIL:
DECLARE BiggestSoFar, NextNumber, Count : IntegerINPUT "Enter first number: ", BiggestSoFarCount ← 1REPEATINPUT "Enter next number: ", NextNumberIF NextNumber > BiggestSoFar THENBiggestSoFar ← NextNumberENDIFCount ← Count + 1UNTIL Count = 10OUTPUT "Largest number is: ", BiggestSoFar
Check Your Understanding: REPEAT-UNTIL Loops
1. Why is REPEAT-UNTIL called a "post-condition" loop? [2 marks]
Answer
- [1 mark] Because the condition is checked at the end (post) of the loop execution
- [1 mark] The loop body executes first, then the condition is tested to decide whether to repeat
- [Additional] This is different from WHILE loops which check the condition at the beginning (pre-condition)
2. What is the key difference between REPEAT-UNTIL and WHILE loops regarding minimum executions? [2 marks]
Answer
- [1 mark] REPEAT-UNTIL loops always execute at least once (condition checked at end)
- [1 mark] WHILE loops might not execute at all if the condition is false initially (condition checked at start)
- [Additional] Example: REPEAT-UNTIL asks for input then checks; WHILE checks condition before asking for input
3. When does a REPEAT-UNTIL loop stop executing? [1 mark]
Answer
- [1 mark] When the condition after UNTIL becomes TRUE
- [Additional] The loop continues while the condition is FALSE, and stops when it becomes TRUE
4. Why might you choose REPEAT-UNTIL over a FOR loop? [2 marks]
Answer
- [1 mark] When you don't know in advance how many times the loop needs to execute
- [1 mark] When the loop needs to run at least once regardless of conditions
- [Additional] Example: Input validation (must ask at least once), menu systems, games with at least one turn
5. What's wrong with this REPEAT-UNTIL loop? [2 marks]
Total ← 0
REPEAT
Total ← Total + 5
UNTIL Total > 20
Answer
- [1 mark] The loop will run forever (infinite loop)
- [1 mark] Total starts at 0, adds 5 each time: 0, 5, 10, 15, 20, 25... It will never be greater than 20? Actually it will stop at 25.
- [Correction] Actually this loop WILL stop: 0→5→10→15→20→25 (25>20 so stops). Nothing wrong!
- [Better example] UNTIL Total < 0 would create infinite loop since Total only increases
WHILE-DO-ENDWHILE Loops
WHILE-DO-ENDWHILE is a pre-condition loop used when we don't know how many times an instruction or set of instructions is to be repeated. This is a conditional loop with a test at the start that repeats until the condition becomes false.
WHILE Loop Structure
- Condition tested at the beginning (pre-condition)
- Loop repeats while condition is TRUE
- Loop stops when condition becomes FALSE
- May not execute at all if condition is false initially
Example: Sum While Positive
This loop continues while the user enters positive numbers. When a non-positive number (0 or negative) is entered, the loop stops. Note: the non-positive number IS added to the total before the loop ends.
WHILE Loop for Average Calculation
Important Notes:
- First number is read BEFORE the loop (pre-condition check needs initial value)
- Loop continues while num ≥ 0 (non-negative)
- Negative number stops the loop
- Count tracks total numbers INCLUDING the negative that stops the loop
Sample Execution:
Total: 0 + 5 + 10 + 15 = 30
Count: 1 → 2 → 3 → 4
Average: 30 / 4 = 7.5
Wait, that includes the -1 in count!
There's a subtle bug: Count starts at 1, increments each iteration including when negative number is entered. So if inputs are 5, 10, 15, -1: Count=4, Total=30, avg=7.5. But -1 shouldn't be counted! Should either not add negative to Total or not increment Count for negative.
Loop Comparison: WHILE vs REPEAT-UNTIL vs FOR
| Feature | FOR-TO-NEXT | WHILE-DO-ENDWHILE | REPEAT-UNTIL |
|---|---|---|---|
| When to use | Known number of iterations | Unknown iterations, condition at start | Unknown iterations, condition at end |
| Condition check | Automatic counter | At beginning (pre-condition) | At end (post-condition) |
| Minimum executions | Could be 0 (if start > end) | Could be 0 (if false initially) | At least 1 (always runs once) |
| Stop condition | Counter passes end value | When condition becomes FALSE | When condition becomes TRUE |
| Example use | Process 30 students' grades | Read file until EOF | Input validation (must ask at least once) |
FOR Loop Thinking
"Do this EXACTLY 10 times"
WHILE Loop Thinking
"Keep doing this AS LONG AS condition is true"
REPEAT-UNTIL Thinking
"Do this, then check if done. If not, do it again"
WHILE Loop Simulator
Simulate a WHILE loop that continues while numbers are positive. The loop checks the condition BEFORE each iteration.
Positive Numbers Added:
How WHILE loop works:
- Check condition: is num > 0?
- If condition is TRUE: execute loop body (add to total, get next number)
- Go back to step 1 and check condition again
- If condition is FALSE: skip loop body and continue after ENDWHILE
- The loop might not execute at all if first num ≤ 0
Home Task
Home Task: Calculating running totals and averages. Take 10 numbers as input and output the sum of these numbers and the average.
Analysis:
- This uses a FOR loop because we know exactly how many numbers: 10
- Total is initialized to 0 before the loop starts
- The loop runs 10 times (Count from 1 to 10)
- Each iteration: ask for a number, add it to Total
- After the loop: output Total, calculate Average (Total/10), output Average
- Note: Average is declared as Integer but should be Real for accurate decimal results
Improved version with Real average:
Check Your Understanding: WHILE Loops
1. Why is WHILE called a "pre-condition" loop? [2 marks]
Answer
- [1 mark] Because the condition is checked at the beginning (pre) of the loop execution
- [1 mark] The condition is tested BEFORE the loop body executes each time
- [Additional] This is different from REPEAT-UNTIL which checks condition at the end (post-condition)
2. When does a WHILE loop stop executing? [1 mark]
Answer
- [1 mark] When the condition becomes FALSE
- [Additional] The loop continues while the condition is TRUE, and stops when it becomes FALSE
3. What is the key advantage of WHILE loops over REPEAT-UNTIL? [2 marks]
Answer
- [1 mark] WHILE loops can skip execution entirely if the condition is false initially
- [1 mark] This prevents unnecessary execution when you might not need to run the loop at all
- [Additional] Example: Processing records from a file that might be empty - WHILE loop won't try to process if file is empty
4. How many times will this loop execute? X ← 5, WHILE X > 0 DO X ← X - 1, ENDWHILE [1 mark]
Answer
- [1 mark] 5 times (when X = 5, 4, 3, 2, 1)
- [Additional] When X becomes 0, condition X > 0 is false, so loop stops
5. Convert this FOR loop to a WHILE loop: FOR Count ← 1 TO 5 OUTPUT Count, NEXT [2 marks]
Answer
- [2 marks]
- [Alternative] Could also use Count < 6 as condition
Nested Loops
A nested loop is a loop inside another loop. Each time the outer loop executes once, the inner loop completes all its iterations. Nested loops are useful for working with grids, tables, or multi-dimensional data.
Example: Symbol Grid
Take as input two numbers and a symbol. Output a grid made up entirely of the chosen symbol, with the number of rows matching the first number input and the number of columns matching the second number input.
Example: Input 3, 7, & results in:
&&&&&&&
&&&&&&&
&&&&&&&
How Nested Loops Work
Execution Order
1. Outer loop starts (RowCount = 1)
2. Inner loop runs completely (ColumnCount = 1 to NumberOfColumns)
3. Output newline
4. Outer loop increments (RowCount = 2)
5. Repeat steps 2-4 until outer loop finishes
Total Iterations
Total iterations = Rows × Columns
For 3 rows × 7 columns = 21 iterations of OUTPUT Symbol
Inner loop runs 3 times × 7 iterations each = 21 total
Real-World Analogy
Like a classroom: Outer loop = each row of desks, Inner loop = each student in that row. You visit each row (outer), and within each row, you visit each student (inner).
For EACH iteration of the outer loop, the inner loop runs COMPLETELY from start to finish.
Nested Loop Grid Visualizer
Watch how nested loops fill a grid row by row. The outer loop controls rows, inner loop controls columns.
Grid Output:
How nested loops execute:
- Outer loop sets row = 1
- Inner loop runs completely: col = 1, 2, 3, ..., Cols
- Output newline after inner loop finishes
- Outer loop increments: row = 2
- Repeat steps 2-4 until row > Rows
- Total iterations = Rows × Cols (15 for 3×5 grid)
Real-Life Example: Multiplication Table
Nested loops perfectly generate multiplication tables:
This creates a 10×10 grid where cell (row, col) contains row×col. Without nested loops, you'd need 100 separate output statements!
Practice Question
Q#1 Write pseudocode to find the sum of series S = 1 + 2 + 3 + ... + N
Analysis and Improvements:
What's good:
- Uses FOR loop correctly - knows exact count (1 to N)
- Correctly adds count to Sum each iteration
- Clear input/output messages
Issues to fix:
- Sum variable is used but not declared
- Sum should be initialized to 0 before the loop
- Variable names: 'count' vs 'Count' - should be consistent
Corrected version:
There's a formula for this: Sum = N×(N+1)/2. For N=100: 100×101/2 = 5050. But the loop approach works for any N and is easier to understand for beginners.
Check Your Understanding: Nested Loops
1. How many times will the OUTPUT statement execute in nested loops with 4 rows and 6 columns? [1 mark]
Answer
- [1 mark] 24 times (4 × 6)
- [Additional] Outer loop runs 4 times, for each outer iteration inner loop runs 6 times: 4 × 6 = 24
2. Why is the OUTPUT Newline statement placed after the inner loop but inside the outer loop? [2 marks]
Answer
- [1 mark] To move to a new line after each complete row is printed
- [1 mark] The inner loop prints all columns in one row, then we need a newline before starting the next row
- [Additional] If OUTPUT Newline was inside inner loop, we'd get each symbol on separate line. If outside both loops, we'd get all symbols on one line then one newline at end.
3. What would happen if we swapped the inner and outer loops in the grid example? [2 marks]
Answer
- [1 mark] We'd print columns first instead of rows
- [1 mark] The grid would be transposed (rows and columns swapped)
- [Additional] With outer=columns, inner=rows: first all row1, row2, row3 for column1, then all rows for column2, etc. Would look like symbols going down first column, then down second column, etc.
4. Write pseudocode using nested loops to output this pattern:
*
**
***
****
***** [3 marks]
Answer
- [3 marks]
- [Key point] Inner loop runs 'row' times, not fixed number. First row: 1 star, second: 2 stars, etc.
5. When would you use nested loops in real programming? Give two examples. [2 marks]
Answer
- [1 mark] Processing 2D arrays or tables (like spreadsheets, game boards, image pixels)
- [1 mark] Generating combinations or permutations (like testing all possible password combinations)
- [Additional] Sorting algorithms (bubble sort uses nested loops), matrix operations, calendar displays
Key Takeaways
- Looping/Repetition allows certain instructions to be repeated either a fixed number of times or until a condition is met
- FOR-TO-NEXT loops are used for counting-based repetition when the number of iterations is known in advance
- WHILE-DO-ENDWHILE loops are pre-condition loops that check the condition at the start and may not execute at all
- REPEAT-UNTIL loops are post-condition loops that check at the end and always execute at least once
- FOR loops are unconditional - the count is fixed at the beginning
- WHILE and REPEAT loops are conditional - they depend on a condition that may change during execution
- Counter variables track how many times a loop has executed
- Accumulator variables (like Total) must be initialized before use in loops
- Nested loops have one loop inside another; each outer iteration completes all inner iterations
- Loop choice depends on the problem: Use FOR for known counts, WHILE for "while true" conditions, REPEAT-UNTIL for "do until true"
- Common applications: Calculating averages, finding max/min values, input validation, generating patterns, processing arrays
- Always ensure loops have a way to terminate to avoid infinite loops
- Pseudocode follows CIE conventions: Keywords in uppercase, indentation shows structure, variables declared before use
Question Bank
1. Compare and contrast FOR, WHILE, and REPEAT-UNTIL loops. Include when you would use each type. [6 marks]
Marking Scheme & Answer
- [2 marks] FOR loops: Counting-based, known number of iterations, unconditional, used when you know exactly how many times to repeat (e.g., process 10 numbers, display 20 rows)
- [2 marks] WHILE loops: Pre-condition, check at start, may not execute at all, used when repetition depends on condition that might be false initially (e.g., read file until EOF, process while data valid)
- [2 marks] REPEAT-UNTIL loops: Post-condition, check at end, always execute at least once, used when you need to do something then check if done (e.g., input validation, menu systems, games with at least one turn)
- [Additional] Key differences: FOR for known count, WHILE for "while true", REPEAT for "do until true". FOR and WHILE can have zero iterations, REPEAT always has ≥1.
2. Write pseudocode that takes numbers as input until the user enters 0, then outputs the average of the positive numbers entered. [5 marks]
Marking Scheme & Answer
Key points: Uses WHILE loop (could use REPEAT), only adds positive numbers to total, counts positive numbers, handles division by zero if no positive numbers.
3. Identify and fix the errors in this pseudocode that should calculate the product of numbers from 1 to N: [4 marks]
INPUT N
FOR X = 1 TO N
PRODUCT = PRODUCT * X
NEXT X
OUTPUT PRODUCT
Marking Scheme & Answer
- [1 mark] PRODUCT variable not declared
- [1 mark] PRODUCT not initialized (should be 1, not 0 for multiplication)
- [1 mark] Assignment should use ← not =
- [1 mark] FOR loop syntax: should be X ← 1 TO N
Important: For multiplication, initialize to 1. For addition, initialize to 0. Uninitialized variables contain garbage values.
4. Write pseudocode using nested loops to output a multiplication table from 1 to 10. [5 marks]
Marking Scheme & Answer
Alternative with better formatting:
5. Explain why this loop is infinite and how to fix it: [3 marks]
X ← 10
WHILE X > 0 DO
OUTPUT X
ENDWHILE
Marking Scheme & Answer
- [1 mark] The loop is infinite because X never changes inside the loop
- [1 mark] The condition X > 0 is always true (X is always 10)
- [1 mark] To fix: Add X ← X - 1 inside the loop to decrement X
Key concept: In WHILE and REPEAT loops, something inside the loop must eventually make the condition false, or the loop will run forever.
6. Write pseudocode that asks for student marks until -1 is entered, then outputs the highest and lowest marks. [6 marks]
Marking Scheme & Answer
Key points: Uses WHILE loop (could use REPEAT), flag variable to handle first mark specially, checks for no marks entered, continues until -1.
7. Convert this FOR loop to a REPEAT-UNTIL loop: [3 marks]
FOR counter ← 1 TO 8
OUTPUT counter * counter
NEXT counter
Marking Scheme & Answer
Alternative with counter = 8: UNTIL counter = 9 (since we increment after output). Both work as long as loop runs exactly 8 times.
8. Write pseudocode that validates user input to be between 1 and 100 inclusive. Keep asking until valid input is received. [4 marks]
Marking Scheme & Answer
Alternative using WHILE:
REPEAT-UNTIL is better here because we need to ask at least once. With WHILE, we must initialize num to an invalid value first.
9. What will be output by this pseudocode? Trace the execution. [4 marks]
X ← 2
WHILE X < 20 DO
OUTPUT X
X ← X * 2
ENDWHILE
Marking Scheme & Answer
- [4 marks] Output will be: 2, 4, 8, 16
- Tracing:
- Start: X = 2, 2 < 20 true → output 2, X = 2×2 = 4
- X = 4, 4 < 20 true → output 4, X = 4×2 = 8
- X = 8, 8 < 20 true → output 8, X = 8×2 = 16
- X = 16, 16 < 20 true → output 16, X = 16×2 = 32
- X = 32, 32 < 20 false → loop ends
- Final output: 2, 4, 8, 16 (each on new line or space-separated)
10. Design pseudocode for a simple number guessing game. The program generates a random number 1-10, user guesses until correct, with feedback "too high" or "too low". [6 marks]
Marking Scheme & Answer
Alternative using REPEAT-UNTIL: