L

9.2 Iteration

Understanding and implementing loops in algorithms using FOR-TO-NEXT, WHILE-DO-ENDWHILE, and REPEAT-UNTIL constructs

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.

Key Insight:

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

FOR X = 1 TO 5
Answer = X * 3
OUTPUT Answer
NEXT
X=1
Answer=3
Output 3
X=1: 1*3=3
X=2: 2*3=6
X=3: 3*3=9
X=4: 4*3=12
X=5: 5*3=15

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
INPUT Student1Attendance
INPUT Student2Attendance
INPUT Student3Attendance
...
INPUT Student30Attendance
30 lines of code!
With FOR Loop
FOR Student = 1 TO 30
INPUT Attendance[Student]
NEXT
Just 3 lines of code!

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.

FOR X = 1 TO 5
Answer = X * 3
OUTPUT Answer
NEXT
X (Counter)
1
Answer
3
Iteration
1/5

How it works: The FOR loop sets up a counter variable (X) that starts at the beginning value. Each time through the loop:

  1. Execute the loop body (calculate Answer = X * 3)
  2. Output the result
  3. Increment X by the step value
  4. Check if X has passed the end value
  5. If not, repeat from step 1

Check Your Understanding: Introduction to Loops

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
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)
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
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
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

Total ← 0
PRINT "Enter the number of values to average"
INPUT Number
FOR Counter ← 1 TO Number
PRINT "Enter value"
INPUT Value
Total ← Total + Value
NEXT Counter
Average ← Total / Number
PRINT "The average of ", Number, " values is ", Average
Algorithm Steps:
  1. Ask for number of values
  2. Loop that number of times
  3. Enter a value in loop
  4. Add the value to Total in loop
  5. Calculate and output average

Fixed Count Example (15 numbers)

DECLARE Total, Count : Integer
DECLARE avg : Real
Total ← 0
FOR Count ← 1 TO 15
INPUT "Enter number", num
Total ← Total + num
NEXT
avg ← Total / 15
OUTPUT "Average of 15 Numbers is:", Avg
Total
0 → 85
Count
1 → 15
num (example)
5, 7, 3...
avg
5.67

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

DECLARE BiggestSoFar, NextNumber, Count : Integer
INPUT "Enter Number", BiggestSoFar
FOR Count ← 1 TO 9
INPUT "Enter Next Number", NextNumber
IF NextNumber > BiggestSoFar THEN
BiggestSoFar ← NextNumber
ENDIF
NEXT
OUTPUT BiggestSoFar
Start
INPUT first number as BiggestSoFar
Count = 1
Count ≤ 9?
INPUT NextNumber
NextNumber > BiggestSoFar?
BiggestSoFar = NextNumber
Count = Count + 1

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.

Example Run:

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:

DECLARE Total, Highest, Score, Count : Integer
DECLARE Average : Real
Total ← 0
Highest ← 0
FOR Count ← 1 TO 25
INPUT "Enter score for student ", Count, Score
Total ← Total + Score
IF Score > Highest THEN
Highest ← Score
ENDIF
NEXT
Average ← Total / 25
OUTPUT "Class Average: ", Average
OUTPUT "Highest Score: ", Highest

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:

  1. Write pseudocode that takes 20 numbers as input and calculates their sum.
  2. Write pseudocode that takes 8 numbers as input and outputs the smallest number.
  3. Write pseudocode to calculate the factorial of a number N (N! = 1 × 2 × 3 × ... × N).
  4. Write pseudocode that outputs the first 10 multiples of 7 (7, 14, 21, ..., 70).
  5. Write pseudocode that takes 5 test scores as input and outputs whether each score is above or below the class average of 65.
Solution:
  1. Sum of 20 numbers:
    Total ← 0
    FOR Count ← 1 TO 20
    INPUT "Enter number: ", Num
    Total ← Total + Num
    NEXT
    OUTPUT "Sum of 20 numbers is: ", Total
  2. Smallest of 8 numbers:
    INPUT "Enter first number: ", Smallest
    FOR Count ← 1 TO 7
    INPUT "Enter next number: ", Num
    IF Num < Smallest THEN
    Smallest ← Num
    ENDIF
    NEXT
    OUTPUT "Smallest number is: ", Smallest
  3. Factorial of N:
    INPUT "Enter number N: ", N
    Factorial ← 1
    FOR Count ← 1 TO N
    Factorial ← Factorial × Count
    NEXT
    OUTPUT N, "! = ", Factorial
  4. First 10 multiples of 7:
    FOR Count ← 1 TO 10
    Multiple ← Count × 7
    OUTPUT Multiple
    NEXT
  5. Scores above/below average:
    Average ← 65
    FOR Count ← 1 TO 5
    INPUT "Enter test score: ", Score
    IF Score ≥ Average THEN
    OUTPUT "Score ", Score, " is above or equal to average"
    ELSE
    OUTPUT "Score ", Score, " is below average"
    ENDIF
    NEXT

Check Your Understanding: FOR Loops

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
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
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
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
Answer
  • [2 marks]
  • FOR Number ← 2 TO 20 STEP 2
    OUTPUT Number
    NEXT
  • [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

REPEAT
// Statements to repeat
// These execute at least once
UNTIL condition
Start
Execute loop body
Condition true?
Yes: Exit loop
No: Repeat
Key Feature:

Loop executes AT LEAST ONCE because condition is checked at the end, not the beginning.

Example: Sum Until Zero

DECLARE Total, num : Integer
Total ← 0
REPEAT
INPUT "Enter a number to add", num
Total ← Total + num
UNTIL num = 0
OUTPUT "Answer after addition is: ", Total
Total
0 → 42
num
5, 12, 7, 18, 0
Iterations
5

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

DECLARE BiggestSoFar, Counter, NextNumber : Integer
INPUT BiggestSoFar
Counter ← 1
REPEAT
INPUT "Enter Number", NextNumber
Counter ← Counter + 1
IF NextNumber > BiggestSoFar THEN
BiggestSoFar ← NextNumber
ENDIF
UNTIL Counter = 10
OUTPUT BiggestSoFar

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

INPUT BiggestSoFar
REPEAT
INPUT NextNumber
IF NextNumber > BiggestSoFar THEN
BiggestSoFar ← NextNumber
ENDIF
UNTIL NextNumber = 0
OUTPUT BiggestSoFar
Important:

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.

Total ← 0
REPEAT
INPUT "Enter number (0 to stop): ", num
Total ← Total + num
UNTIL num = 0
OUTPUT "Total sum: ", Total
Total
0
Current num
-
Iteration
0
Condition
num = 0? No
Numbers Entered:

How REPEAT-UNTIL works:

  1. Execute the loop body (input number, add to total)
  2. Check the condition: is num = 0?
  3. If condition is TRUE: exit the loop
  4. If condition is FALSE: go back to step 1 and repeat
  5. 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:

  1. Write pseudocode that asks for passwords until the correct password "Secret123" is entered.
  2. Write pseudocode that takes numbers as input and counts how many are entered until a negative number is input.
  3. Write pseudocode for a simple calculator that repeatedly asks for two numbers and an operation (+, -, *, /) until the user enters 'Q' for quit.
  4. Write pseudocode that keeps asking for test scores (0-100) until a valid score is entered (valid means between 0 and 100 inclusive).
  5. Convert the FOR loop example for finding largest of 10 numbers to use REPEAT-UNTIL instead.
Solution:
  1. Password check:
    DECLARE password : String
    REPEAT
    INPUT "Enter password: ", password
    UNTIL password = "Secret123"
    OUTPUT "Access granted"
  2. Count numbers until negative:
    DECLARE num, count : Integer
    count ← 0
    REPEAT
    INPUT "Enter a number: ", num
    count ← count + 1
    UNTIL num < 0
    OUTPUT "Total numbers entered: ", count - 1
  3. Simple calculator:
    DECLARE num1, num2, result : Real
    DECLARE op : Char
    REPEAT
    INPUT "Enter first number: ", num1
    INPUT "Enter second number: ", num2
    INPUT "Enter operation (+, -, *, /) or Q to quit: ", op
    IF op = '+' THEN result ← num1 + num2
    ELSEIF op = '-' THEN result ← num1 - num2
    ELSEIF op = '*' THEN result ← num1 * num2
    ELSEIF op = '/' THEN result ← num1 / num2
    ENDIF
    OUTPUT "Result: ", result
    UNTIL op = 'Q'
  4. Input validation:
    DECLARE score : Integer
    REPEAT
    INPUT "Enter test score (0-100): ", score
    UNTIL score ≥ 0 AND score ≤ 100
    OUTPUT "Valid score accepted: ", score
  5. Convert FOR to REPEAT-UNTIL:
    DECLARE BiggestSoFar, NextNumber, Count : Integer
    INPUT "Enter first number: ", BiggestSoFar
    Count ← 1
    REPEAT
    INPUT "Enter next number: ", NextNumber
    IF NextNumber > BiggestSoFar THEN
    BiggestSoFar ← NextNumber
    ENDIF
    Count ← Count + 1
    UNTIL Count = 10
    OUTPUT "Largest number is: ", BiggestSoFar

Check Your Understanding: REPEAT-UNTIL Loops

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)
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
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
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
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

X ← 0
WHILE X < 6 DO
X ← X + 1
Answer ← X * 3
OUTPUT X, Answer
ENDWHILE
Start
X < 6?
X ← X + 1
Answer ← X * 3
OUTPUT X, Answer
Loop back
Key Features:
  • 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

DECLARE Total, num : Integer
Total ← 0
num ← 1
WHILE num > 0 DO
PRINT "Please Input Number greater than zero"
INPUT num
Total ← Total + num
ENDWHILE
PRINT "Total sum is:", Total
Total
0 → 27
num
5, 8, 9, 5, -1
Loop runs
4 times

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

DECLARE Total, Count, num : Integer
DECLARE avg : Real
Total ← 0
PRINT "Enter Number to Add"
INPUT num
Count ← 1
WHILE num ≥ 0 DO
Total ← Total + num
INPUT num
Count ← Count + 1
ENDWHILE
avg ← Total / Count
PRINT "The Average is:", avg
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:
Inputs: 5, 10, 15, -1
Total: 0 + 5 + 10 + 15 = 30
Count: 1 → 2 → 3 → 4
Average: 30 / 4 = 7.5
Wait, that includes the -1 in count!
Bug Alert!

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.

Total ← 0
INPUT "Enter first number: ", num
WHILE num > 0 DO
Total ← Total + num
INPUT "Enter next number: ", num
ENDWHILE
OUTPUT "Total sum of positive numbers: ", Total
Total
0
Current num
-
Iteration
0
Condition
num > 0? -
Positive Numbers Added:

How WHILE loop works:

  1. Check condition: is num > 0?
  2. If condition is TRUE: execute loop body (add to total, get next number)
  3. Go back to step 1 and check condition again
  4. If condition is FALSE: skip loop body and continue after ENDWHILE
  5. 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.

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

Check Your Understanding: WHILE Loops

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)
Answer
  • [1 mark] When the condition becomes FALSE
  • [Additional] The loop continues while the condition is TRUE, and stops when it becomes FALSE
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
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
Answer
  • [2 marks]
  • Count ← 1
    WHILE Count ≤ 5 DO
    OUTPUT Count
    Count ← Count + 1
    ENDWHILE
  • [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.

DECLARE NumberOfRows, NumberOfColumns, ColumnCount, RowCount : Integer
DECLARE Symbol : Char
INPUT "Enter number of Row", NumberOfRows
INPUT "Enter Number of Column", NumberOfColumns
INPUT "Enter your symbol", Symbol
FOR RowCount ← 1 TO NumberOfRows
FOR ColumnCount ← 1 TO NumberOfColumns
OUTPUT Symbol // without moving to next line
NEXT ColumnCount
OUTPUT Newline // move to the next line
NEXT RowCount

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).

Key Insight:

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.

Rows ← 3, Cols ← 5
FOR row ← 1 TO Rows
FOR col ← 1 TO Cols
OUTPUT "(" + row + "," + col + ")"
NEXT col
OUTPUT Newline
NEXT row
Current row
1
Current col
1
Total cells
15
Cells done
0
Grid Output:
Format: (row,column)

How nested loops execute:

  1. Outer loop sets row = 1
  2. Inner loop runs completely: col = 1, 2, 3, ..., Cols
  3. Output newline after inner loop finishes
  4. Outer loop increments: row = 2
  5. Repeat steps 2-4 until row > Rows
  6. Total iterations = Rows × Cols (15 for 3×5 grid)

Real-Life Example: Multiplication Table

Nested loops perfectly generate multiplication tables:

// Generate 10x10 multiplication table
FOR row ← 1 TO 10
FOR col ← 1 TO 10
product ← row * col
OUTPUT product (formatted)
NEXT col
OUTPUT newline
NEXT row

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

DECLARE Num, Count : Integer
Print "Enter number till you want to add series of number"
Input Num
For count ← 1 To Num
Sum ← Sum + count
Next Count
Print "Sum of Series of Number till", Num, " is =", Sum
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:
DECLARE Num, Count, Sum : Integer
Sum ← 0
PRINT "Enter number till you want to add series of number"
INPUT Num
FOR Count ← 1 TO Num
Sum ← Sum + Count
NEXT Count
PRINT "Sum of series 1 to ", Num, " is = ", Sum
Mathematical Insight:

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

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
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.
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.
Answer
  • [3 marks]
  • DECLARE row, col : Integer
    FOR row ← 1 TO 5
    FOR col ← 1 TO row
    OUTPUT "*"
    NEXT col
    OUTPUT Newline
    NEXT row
  • [Key point] Inner loop runs 'row' times, not fixed number. First row: 1 star, second: 2 stars, etc.
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

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.
Marking Scheme & Answer
DECLARE num, total, count : Integer
DECLARE average : Real
total ← 0
count ← 0
INPUT "Enter a number (0 to stop): ", num
WHILE num ≠ 0 DO
IF num > 0 THEN
total ← total + num
count ← count + 1
ENDIF
INPUT "Enter next number (0 to stop): ", num
ENDWHILE
IF count > 0 THEN
average ← total / count
OUTPUT "Average of positive numbers: ", average
ELSE
OUTPUT "No positive numbers entered"
ENDIF

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.

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
DECLARE N, X, PRODUCT : Integer
INPUT N
PRODUCT ← 1
FOR X ← 1 TO N
PRODUCT ← PRODUCT * X
NEXT X
OUTPUT PRODUCT

Important: For multiplication, initialize to 1. For addition, initialize to 0. Uninitialized variables contain garbage values.

Marking Scheme & Answer
DECLARE row, col, product : Integer
FOR row ← 1 TO 10
FOR col ← 1 TO 10
product ← row * col
OUTPUT product (with formatting/spacing)
NEXT col
OUTPUT Newline // Move to next row
NEXT row

Alternative with better formatting:

DECLARE row, col : Integer
OUTPUT "Multiplication Table 1-10:"
OUTPUT Newline
FOR row ← 1 TO 10
FOR col ← 1 TO 10
// Output with fixed width for alignment
OUTPUT (row * col) formatted in 4 spaces
NEXT col
OUTPUT Newline
NEXT row
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
X ← 10
WHILE X > 0 DO
OUTPUT X
X ← X - 1 // This fixes the infinite loop
ENDWHILE

Key concept: In WHILE and REPEAT loops, something inside the loop must eventually make the condition false, or the loop will run forever.

Marking Scheme & Answer
DECLARE mark, highest, lowest : Integer
DECLARE firstMark : Boolean
firstMark ← TRUE
INPUT "Enter student mark (-1 to stop): ", mark
WHILE mark ≠ -1 DO
IF firstMark = TRUE THEN
highest ← mark
lowest ← mark
firstMark ← FALSE
ELSE
IF mark > highest THEN
highest ← mark
ENDIF
IF mark < lowest THEN
lowest ← mark
ENDIF
ENDIF
INPUT "Enter next mark (-1 to stop): ", mark
ENDWHILE
IF firstMark = FALSE THEN // At least one mark entered
OUTPUT "Highest mark: ", highest
OUTPUT "Lowest mark: ", lowest
ELSE
OUTPUT "No marks entered"
ENDIF

Key points: Uses WHILE loop (could use REPEAT), flag variable to handle first mark specially, checks for no marks entered, continues until -1.

Marking Scheme & Answer
DECLARE counter : Integer
counter ← 1
REPEAT
OUTPUT counter * counter
counter ← counter + 1
UNTIL counter > 8

Alternative with counter = 8: UNTIL counter = 9 (since we increment after output). Both work as long as loop runs exactly 8 times.

counter ← 1
REPEAT
OUTPUT counter * counter
counter ← counter + 1
UNTIL counter = 9
Marking Scheme & Answer
DECLARE num : Integer
REPEAT
INPUT "Enter a number between 1 and 100: ", num
UNTIL num ≥ 1 AND num ≤ 100
OUTPUT "Valid number accepted: ", num

Alternative using WHILE:

DECLARE num : Integer
num ← 0 // Initialize to invalid value
WHILE num < 1 OR num > 100 DO
INPUT "Enter a number between 1 and 100: ", num
ENDWHILE
OUTPUT "Valid number accepted: ", num

REPEAT-UNTIL is better here because we need to ask at least once. With WHILE, we must initialize num to an invalid value first.

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)
Marking Scheme & Answer
DECLARE target, guess, attempts : Integer
// Generate random number 1-10 (pseudocode varies by language)
target ← RANDOM(1, 10) // Assume this function exists
attempts ← 0
guess ← 0 // Initialize to something not 1-10
WHILE guess ≠ target DO
INPUT "Guess a number 1-10: ", guess
attempts ← attempts + 1
IF guess < target THEN
OUTPUT "Too low, try again"
ELSEIF guess > target THEN
OUTPUT "Too high, try again"
ENDIF
ENDWHILE
OUTPUT "Correct! You guessed ", target, " in ", attempts, " attempts"

Alternative using REPEAT-UNTIL:

DECLARE target, guess, attempts : Integer
target ← RANDOM(1, 10)
attempts ← 0
REPEAT
INPUT "Guess a number 1-10: ", guess
attempts ← attempts + 1
IF guess < target THEN
OUTPUT "Too low"
ELSEIF guess > target THEN
OUTPUT "Too high"
ENDIF
UNTIL guess = target
OUTPUT "Correct! Took ", attempts, " attempts"