Loop Structures: FOR, WHILE and REPEAT Loops

Master the art of repetition in programming - a essential CSEC IT skill!

Learning Objectives

By the end of this article, you should be able to:

  • Explain why loops are used in algorithms and programming
  • Distinguish between FOR, WHILE, and REPEAT loop structures
  • Write looping structures using CSEC-style pseudocode
  • Trace loop execution step-by-step using trace tables
  • Answer CSEC exam questions involving loops with confidence
What is a Loop?

A loop (also called iteration) is a programming structure that repeats a block of code multiple times. Instead of writing the same instructions over and over, we use a loop to execute them efficiently.

1

Introduction to Loop Structures

Why Do We Need Repetition in Algorithms?

Imagine you need to calculate the total marks for 30 students in a class. Without loops, you would need to write 30 separate input statements and 30 separate addition operations. Loops allow us to write the code once and repeat it automatically for each student.

Real-Life Loops

We use loops in everyday life without even realizing it:

Real-Life Task The "Loop"
Taking attendance for 30 students Call each name until you reach the end of the roll
Shuffling a deck of cards Repeat the shuffle motion multiple times
Checking emails Refresh inbox repeatedly until new mail arrives
Setting an alarm Ring every 24 hours (forever loop)

The Problem Without Loops

Consider calculating the average of 100 numbers without using a loop:

// Calculating average WITHOUT loops (tedious!)
INPUT Num1
INPUT Num2
INPUT Num3
... (97 more input statements!)
Total = Num1 + Num2 + Num3 + ... (100 variables!)
Average = Total / 100

This approach is impractical! Loops solve this problem elegantly.

Caribbean Context: In a Jamaican school, a teacher might need to calculate the average CSEC grades for all students in a cohort. Rather than writing separate instructions for each student, a loop can process all student records efficiently!
2

Why Loops Are Important

Benefits of Using Loops

Benefit Explanation
Reduces Code Repetition Write once, execute many times
Improves Efficiency Less code means faster execution and easier maintenance
Increases Clarity Code is easier to read and understand
Enables Scalability Can process 10 or 10,000 items with the same code
Reduces Errors Fewer chances for mistakes when copying and pasting
The Danger of Infinite Loops

An infinite loop is a loop that never ends because its termination condition is never met. This can cause programs to freeze or crash!

Example of an infinite loop:

// INFINITE LOOP - DO NOT RUN!
Counter = 1
WHILE Counter > 0 DO
    OUTPUT Counter
    // Counter never decreases, so condition always TRUE
ENDWHILE

To avoid infinite loops, always ensure the loop variable changes toward the termination condition!

Preventing Infinite Loops

Always ask these questions when writing a loop:

  • What starts the loop? (initial value)
  • What continues the loop? (condition)
  • What ends the loop? (how the variable changes)
3

The FOR Loop (Count-Controlled Loop)

What is a FOR Loop?

The FOR loop is a count-controlled loop that executes a specific number of times. The loop variable automatically increments (or decrements) with each iteration, making it perfect when you know exactly how many times to repeat.

When to Use a FOR Loop

Use a FOR loop when:

  • You know the exact number of iterations needed
  • You need to count through a range of values
  • The loop depends on a numeric counter

FOR Loop Syntax

FOR counter ← start TO end DO
    statement(s) to repeat
ENDFOR

Example 1: Counting from 1 to 5

Let's trace through a simple FOR loop that counts from 1 to 5:

FOR Count ← 1 TO 5 DO
    OUTPUT Count
ENDFOR

Expected Output:

1
2
3
4
5

Step-by-Step Trace Table

Iteration Count (Before) Condition Check Output Count (After)
1 1 1 ≤ 5? Yes 1 2
2 2 2 ≤ 5? Yes 2 3
3 3 3 ≤ 5? Yes 3 4
4 4 4 ≤ 5? Yes 4 5
5 5 5 ≤ 5? Yes 5 6
6 6 6 ≤ 5? No → EXIT LOOP - -

Example 2: Summing Five Numbers

A practical example calculating the sum of five numbers:

// Calculate the sum of 5 numbers
Total = 0

FOR Num ← 1 TO 5 DO
    INPUT Number
    Total = Total + Number
ENDFOR

OUTPUT "The sum is: ", Total

Sample Execution: If user enters 10, 20, 30, 40, 50, the output will be "The sum is: 150"

FOR Loop with STEP

You can skip values using the STEP keyword:

// Counting by 2s (even numbers only)
FOR Num ← 2 TO 10 STEP 2 DO
    OUTPUT Num
ENDFOR

Output: 2, 4, 6, 8, 10

Remember: In CSEC pseudocode, FOR loops always start at the given value and continue until the end value is reached. The counter automatically increases by 1 (or the STEP value) after each iteration!
4

The WHILE Loop (Pre-Test Loop)

What is a WHILE Loop?

The WHILE loop is a condition-controlled loop that checks its condition before each iteration. If the condition is FALSE from the start, the loop body may never execute!

When to Use a WHILE Loop

Use a WHILE loop when:

  • You don't know how many iterations are needed
  • The loop depends on user input or external conditions
  • The loop should only run if a condition is true

WHILE Loop Syntax

WHILE condition DO
    statement(s) to repeat
ENDWHILE

Example 1: Password Validation

A login system that keeps asking for the password until correct:

// Password validation loop
CorrectPassword = "CSEC2024"
Attempt = 0

WHILE Attempt < 3 DO
    INPUT UserPassword
    IF UserPassword = CorrectPassword THEN
        OUTPUT "Access Granted!"
        EXIT  // Exit the loop immediately
    ELSE
        OUTPUT "Incorrect password. Try again."
    ENDIF
    Attempt = Attempt + 1
ENDWHILE

OUTPUT "Account locked. Too many attempts."
Important: WHILE May Execute Zero Times!

Because WHILE checks the condition before executing, if the condition is FALSE initially, the loop body never runs.

Example:

Counter = 5
WHILE Counter < 3 DO  // FALSE immediately!
    OUTPUT "This never prints"
ENDWHILE
OUTPUT "Done"  // This prints instead

Example 2: Reading Until Zero

Processing numbers until the user enters 0:

// Read numbers until zero is entered
INPUT Number
Sum = 0
Count = 0

WHILE Number <> 0 DO
    Sum = Sum + Number
    Count = Count + 1
    INPUT Number
ENDWHILE

OUTPUT "Count: ", Count, ", Sum: ", Sum

Trace Table Example

Step Number Sum Count Condition (Number <> 0) Output
Init 5 0 0 - -
1 5 5 1 5 <> 0 = TRUE -
2 3 8 2 3 <> 0 = TRUE -
3 0 8 2 0 <> 0 = FALSE → EXIT "Count: 2, Sum: 8"
CSEC Tip

Remember: WHILE loops are pre-test loops. The condition is checked BEFORE each iteration. This is different from REPEAT-UNTIL!

5

The REPEAT-UNTIL Loop (Post-Test Loop)

What is a REPEAT-UNTIL Loop?

The REPEAT-UNTIL loop is a post-test loop that checks its condition after each iteration. This means the loop body always executes at least once, even if the condition is initially false!

When to Use a REPEAT-UNTIL Loop

Use a REPEAT-UNTIL loop when:

  • You need the loop to run at least once
  • You're asking for user input that must be collected before validation
  • Creating menus or dialogs that should show before asking to continue

REPEAT-UNTIL Syntax

REPEAT
    statement(s) to repeat
UNTIL condition

Example 1: Menu System

A restaurant menu that displays options until the user makes a selection:

// Restaurant menu system
REPEAT
    OUTPUT "=== MAIN MENU ==="
    OUTPUT "1. Chicken Curry"
    OUTPUT "2. Jerk Pork"
    OUTPUT "3. Fried Chicken"
    OUTPUT "4. Exit"
    INPUT "Enter your choice (1-4): ", Choice
UNTIL Choice >= 1 AND Choice <= 3

OUTPUT "You selected option ", Choice

Example 2: Validating Age Input

Asking for age until a valid value (0-120) is entered:

// Validate age input - always asks at least once
REPEAT
    INPUT "Enter your age: ", Age
    IF Age < 0 OR Age > 120 THEN
        OUTPUT "Invalid age! Please try again."
    ENDIF
UNTIL Age >= 0 AND Age <= 120

OUTPUT "Valid age entered: ", Age
REPEAT-UNTIL Always Executes At Least Once!

Unlike WHILE loops, REPEAT-UNTIL executes the body first, then checks the condition. This guarantees at least one iteration.

Counter = 10
REPEAT
    OUTPUT "Counter is ", Counter  // This WILL print!
    Counter = Counter - 1
UNTIL Counter < 5  // Condition checked AFTER

Output: Counter is 10, Counter is 9, Counter is 8, Counter is 7, Counter is 6, Counter is 5

REPEAT-UNTIL vs WHILE

Feature WHILE Loop REPEAT-UNTIL Loop
Condition check Before each iteration After each iteration
Minimum executions 0 (may not run at all) 1 (always runs at least once)
Loop continues when Condition is TRUE Condition is FALSE
Best for When you may not need to iterate When you must execute at least once
Remember: The REPEAT-UNTIL loop continues until the condition becomes TRUE. So the loop stops when condition = TRUE. This is the opposite of WHILE, which continues while condition = TRUE!
6

Comparing Loop Structures

Loop Type Comparison Table

Loop Type Control Method Condition Check Minimum Runs Best Use Case
FOR Count-controlled Before (automatic counter) 0 if start > end Known number of iterations
WHILE Condition-controlled Before each iteration 0 (may skip entirely) Unknown iterations, may skip
REPEAT-UNTIL Condition-controlled After each iteration 1 (always runs) Must execute at least once

When to Use Each Loop

Scenario Recommended Loop Reason
Process 50 student records FOR Exactly 50 iterations needed
Read until user enters "quit" WHILE Unknown number of inputs
Display menu, get valid choice REPEAT-UNTIL Must show menu at least once
Calculate factorial (n!) FOR Fixed number of multiplications
Validate password entry REPEAT-UNTIL Must attempt at least once
Exam Question Alert!

CSEC examiners often ask students to convert between loop types or identify which loop is appropriate for a given scenario. Know the strengths and weaknesses of each loop type!

7

Loops in Flowcharts

How Loops Are Represented

All loops in flowcharts use the decision diamond to represent the loop condition. The flow returns to the decision point after each iteration.

FOR Loop Flowchart

START Counter = 1 Counter <= 5? YES OUTPUT Counter Counter = Counter + 1 NO END

FOR Loop Flowchart: The counter is initialized, then checked against a condition. If true, the process runs and the counter updates, looping back to the decision.

WHILE Loop Flowchart

START Condition TRUE? YES Process Statements NO END

WHILE Loop Flowchart: The condition is checked BEFORE the process runs. If FALSE, the loop body is never executed.

REPEAT-UNTIL Flowchart

START Process/Statements (Always executes at least once) Condition TRUE? YES (Exit) NO (Loop) END

REPEAT-UNTIL Flowchart: The process executes first, then the condition is checked. The loop continues while the condition is FALSE, exiting when TRUE.

8

Tracing Loop Execution

What is a Trace Table?

A trace table is a systematic way to track variable values through each step of an algorithm's execution. For loops, we track the loop counter and other variables at each iteration.

Example: FOR Loop Trace Table

Algorithm:

// Calculate the square of numbers 1 to 4
FOR Num ← 1 TO 4 DO
    Square = Num * Num
    OUTPUT Square
ENDFOR
Iteration Num (Before) Square = Num * Num Output Num (After)
1 1 1 * 1 = 1 1 2
2 2 2 * 2 = 4 4 3
3 3 3 * 3 = 9 9 4
4 4 4 * 4 = 16 16 5 (loop ends)

Example: WHILE Loop Trace Table

Algorithm:

Counter = 1
Total = 0

WHILE Counter <= 3 DO
    Total = Total + Counter
    Counter = Counter + 1
ENDWHILE

OUTPUT Total
Step Counter Total Condition (Counter <= 3) Action
Initial 1 0 - -
1 1 1 1 <= 3 = TRUE Add 1, Counter = 2
2 2 3 2 <= 3 = TRUE Add 2, Counter = 3
3 3 6 3 <= 3 = TRUE Add 3, Counter = 4
4 4 6 4 <= 3 = FALSE EXIT LOOP
Final - - - OUTPUT: 6

Example: REPEAT-UNTIL Trace Table

Algorithm:

Number = 0

REPEAT
    INPUT Number
    OUTPUT Number
UNTIL Number > 10

Assume user inputs: 5, 15

Iteration Number (Before) Process Number (After) Condition (Number > 10) Action
1 0 INPUT 5, OUTPUT 5 5 5 > 10 = FALSE Continue loop
2 5 INPUT 15, OUTPUT 15 15 15 > 10 = TRUE EXIT LOOP
CSEC Exam Tip

Trace tables are a CSEC favourite! Practice creating trace tables for all three loop types. Pay special attention to when the condition is checked and how variables update.

9

Nested Loops (Introduction)

What are Nested Loops?

A nested loop is a loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.

When to Use Nested Loops

  • Processing 2D data (tables, grids, matrices)
  • Creating patterns and shapes
  • Comparing every pair of items in a list
  • Multiplication tables, timetables

Example: Multiplication Table

Creating a multiplication table (1 to 3):

// Outer loop: rows (1 to 3)
FOR Row ← 1 TO 3 DO
    // Inner loop: columns (1 to 5)
    FOR Col ← 1 TO 5 DO
        Product = Row * Col
        OUTPUT Row, "*", Col, "=", Product
    ENDFOR
ENDFOR

How Many Times Does the Inner Loop Execute?

If the outer loop runs M times and the inner loop runs N times, the total iterations = M × N

In our example: 3 (rows) × 5 (columns) = 15 total iterations

Step-by-Step Execution

Outer Loop (Row) Inner Loop (Col) Executions Total So Far
Row = 1 Col = 1, 2, 3, 4, 5 5
Row = 2 Col = 1, 2, 3, 4, 5 10
Row = 3 Col = 1, 2, 3, 4, 5 15
Warning: Performance Impact!

Nested loops can create many iterations quickly. A 100×100 loop executes 10,000 times! Always consider whether nested loops are necessary for your problem.

10

Interactive Learning Activities

Test Your Knowledge!

🔮 How Many Times Will It Loop? - Question 1

How many times will this loop execute?

FOR Count ← 1 TO 10 DO
    OUTPUT Count
ENDFOR

Answer: 10 times

The loop runs for Count = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

🔮 How Many Times Will It Loop? - Question 2

How many times will this loop execute?

Num = 5
WHILE Num > 0 DO
    Num = Num - 1
ENDWHILE

Answer: 5 times

Iteration 1: Num = 5 → 4

Iteration 2: Num = 4 → 3

Iteration 3: Num = 3 → 2

Iteration 4: Num = 2 → 1

Iteration 5: Num = 1 → 0 (stops because 0 > 0 is FALSE)

🔮 Predict the Output - Question 1

What is the output of this code?

Total = 0
FOR Num ← 1 TO 3 DO
    Total = Total + Num
ENDFOR
OUTPUT Total

Output: 6

Iteration 1: Total = 0 + 1 = 1

Iteration 2: Total = 1 + 2 = 3

Iteration 3: Total = 3 + 3 = 6

🔍 Identify the Error

Find the error in this code:

Counter = 0
WHILE Counter < 5 DO
    OUTPUT Counter
ENDWHILE

Error: INFINITE LOOP!

Counter never changes, so the condition Counter < 5 is always TRUE.

Fix:

Counter = 0
WHILE Counter < 5 DO
    OUTPUT Counter
    Counter = Counter + 1  // Add this line!
ENDWHILE

🎯 Choose the Right Loop

Which loop type would you use for each scenario?

  1. Display a menu and ask for input until a valid choice is made
  2. Process exactly 30 student records from a class list
  3. Read numbers from a file until you reach the end (unknown count)

Answers:

  1. REPEAT-UNTIL - Must show menu at least once, then repeat until valid choice
  2. FOR - Exactly 30 iterations needed (count-controlled)
  3. WHILE - Unknown number of iterations, read until end-of-file condition
11

Common Student Mistakes

Mistake 1: Infinite Loops

Forgetting to update the loop counter leads to infinite loops.

Wrong:

Num = 1
WHILE Num <= 10 DO
    OUTPUT Num
    // Num never changes!
ENDWHILE

Correct:

Num = 1
WHILE Num <= 10 DO
    OUTPUT Num
    Num = Num + 1  // Update counter!
ENDWHILE
Mistake 2: Off-by-One Errors

Getting the start or end values wrong in FOR loops.

Problem: FOR 1 TO 10 gives 10 iterations, not 9 or 11!

Common Error: Thinking 1 TO 10 gives 9 iterations (it doesn't!).

Loop Range Number of Iterations
1 TO 10 10 (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
5 TO 5 1 (just 5)
10 TO 1 0 (need STEP -1)
Mistake 3: Using the Wrong Loop Type

Using FOR when you need REPEAT-UNTIL (or vice versa).

  • Use FOR when you know the EXACT count
  • Use WHILE when you may not need to iterate at all
  • Use REPEAT-UNTIL when you MUST iterate at least once
Mistake 4: Wrong Keywords

CSEC pseudocode uses specific keywords:

  • FOR loops: FOR...TO...ENDFOR or FOR...TO...DO...ENDFOR
  • WHILE loops: WHILE...DO...ENDWHILE
  • REPEAT loops: REPEAT...UNTIL

Don't mix up ENDWHILE with ENDFOR or forget UNTIL in REPEAT loops!

12

CSEC Exam Focus

How Loops Appear in CSEC Exams

Loops are tested in multiple ways across CSEC papers:

1. Multiple-Choice Questions (Paper 1)

  • Identifying how many times a loop executes
  • Selecting the correct loop type for a scenario
  • Recognizing infinite loops
  • Understanding loop terminology

2. Trace Tables (Paper 2)

  • Completing trace tables for loop algorithms
  • Tracking variable values through iterations
  • Determining final output

3. Pseudocode Questions (Paper 2)

  • Writing loop-based algorithms
  • Converting between loop types
  • Fixing loop errors
  • Completing partially-written code

4. Flowchart Questions (Paper 2)

  • Interpreting loop flowcharts
  • Drawing flowcharts with loops
  • Tracing execution paths
Exam Success Tips
  • Read the question carefully: Know exactly what the loop should do
  • Trace step by step: Write down variable values at each iteration
  • Check termination: Verify the loop will eventually end
  • Practice daily: More practice = better exam performance!
13

CSEC-Style Exam Practice Questions

Test yourself with these exam-style questions. Click to reveal answers!

Question 1: Multiple Choice

How many times will the following loop execute?

FOR Num ← 3 TO 7 DO
    OUTPUT Num
ENDFOR
  1. 4 times
  2. 5 times
  3. 6 times
  4. 7 times

Answer: B - 5 times

Iterations: 3, 4, 5, 6, 7 (5 values total)

Question 2: Multiple Choice

Which loop type always executes at least once?

  1. FOR loop
  2. WHILE loop
  3. REPEAT-UNTIL loop
  4. All loops execute at least once

Answer: C - REPEAT-UNTIL loop

REPEAT-UNTIL checks the condition AFTER each iteration, so it always runs at least once.

Question 3: Trace Table

Complete a trace table for the following pseudocode. What is the final value of Total?

Total = 0
FOR Num ← 1 TO 4 DO
    IF Num MOD 2 = 0 THEN
        Total = Total + Num
    ENDIF
ENDFOR
OUTPUT Total

Answer: 6

Num Num MOD 2 = 0? Action Total
1 1 MOD 2 = 1 ≠ 0 Skip 0
2 2 MOD 2 = 0 Add 2 2
3 3 MOD 2 = 1 ≠ 0 Skip 2
4 4 MOD 2 = 0 Add 4 6

Final Output: 6

Question 4: Pseudocode Writing

Write pseudocode using a FOR loop to calculate and display the sum of all even numbers from 2 to 20.

Sample Answer:

// Sum of even numbers from 2 to 20
Sum = 0

FOR Num ← 2 TO 20 STEP 2 DO
    Sum = Sum + Num
ENDFOR

OUTPUT "Sum of even numbers (2-20): ", Sum

Alternative (without STEP):

FOR Num ← 1 TO 20 DO
    IF Num MOD 2 = 0 THEN
        Sum = Sum + Num
    ENDIF
ENDFOR

Question 5: Trace Table

Complete the trace table and determine the output:

Count = 1
WHILE Count < 4 DO
    OUTPUT Count
    Count = Count + 2
ENDWHILE

Answer: 1, 3 (on separate lines)

Iteration Count (Before) Count < 4? Output Count (After)
1 1 TRUE 1 3
2 3 TRUE 3 5
3 5 FALSE → EXIT - -

Question 6: Flowchart/Pseudocode Conversion

Draw or describe the flowchart for a REPEAT-UNTIL loop that repeatedly asks for a password until the user enters "CSEC".

Answer:

Pseudocode:

REPEAT
    INPUT "Enter password: ", UserInput
    IF UserInput <> "CSEC" THEN
        OUTPUT "Wrong password, try again"
    ENDIF
UNTIL UserInput = "CSEC"

OUTPUT "Access Granted!"

Flowchart Description:

  1. Start
  2. Rectangle: "INPUT password"
  3. Decision Diamond: "Password = 'CSEC'?"
  4. If NO: Output "Wrong password", arrow back to INPUT
  5. If YES: Arrow to "Output Access Granted"
  6. End

Question 7: Short Answer

State TWO differences between WHILE and REPEAT-UNTIL loops.

Answer (any two):

  1. Condition timing: WHILE checks before (pre-test); REPEAT-UNTIL checks after (post-test)
  2. Minimum executions: WHILE may execute 0 times; REPEAT-UNTIL always executes at least once
  3. Loop condition logic: WHILE continues while TRUE; REPEAT-UNTIL continues until TRUE (stops when TRUE)

Question 8: Algorithm Problem

A school has 25 students. Write pseudocode using a FOR loop to:

  1. Input each student's CSEC Mathematics mark (0-100)
  2. Calculate the class average
  3. Count how many students passed (mark ≥ 50)

Sample Answer:

// CSEC Math marks analysis for 25 students
TotalMarks = 0
PassCount = 0

FOR Student ← 1 TO 25 DO
    INPUT "Enter mark for student ", Student, ": ", Mark
    TotalMarks = TotalMarks + Mark
    
    IF Mark >= 50 THEN
        PassCount = PassCount + 1
    ENDIF
ENDFOR

Average = TotalMarks / 25

OUTPUT "Class Average: ", Average
OUTPUT "Number of Students Who Passed: ", PassCount
14

Summary

Key Points to Remember
  • Loops allow code to repeat multiple times without rewriting
  • FOR loops are count-controlled - use when you know the exact number of iterations
  • WHILE loops are pre-test loops - may execute 0 times if condition is false
  • REPEAT-UNTIL loops are post-test loops - always execute at least once
  • Infinite loops occur when the termination condition is never met
  • Nested loops have one loop inside another (multiply iterations)
  • Trace tables help track variable values through loop execution
Keep Practicing!

Loop structures are fundamental to programming and frequently tested in CSEC exams. Practice writing different loop types, creating trace tables, and identifying loop errors. The more you practice, the more confident you'll become!

Scroll to Top