SLIDE 1
CSZone.co.uk
Click to advance · Arrow keys also work
Cambridge IGCSE 0478 · Topic 8 · 8.1c

Iteration in
Programming

FOR Loop · WHILE Loop · REPEAT UNTIL · Choosing the Right Loop

CSZoneCambridge IGCSE Computer Science 0478
FOR Loop — Count-Controlled

When You Know How Many Times

// Sum numbers 1 to 10
total ← 0
FOR i ← 1 TO 10
total ← total + i
NEXT i
OUTPUT "Sum = ", total

// Countdown (STEP -1)
FOR i ← 10 TO 1 STEP -1
OUTPUT i
NEXT i
OUTPUT "Blastoff!"
Use FOR when the number of repetitions is known before the loop starts
STEP can be used to change the increment: STEP 2 counts 1, 3, 5, 7…; STEP -1 counts down
WHILE and REPEAT UNTIL

Condition-Controlled Loops

// WHILE — check BEFORE entering
total ← 0
INPUT number
WHILE number <> -1 DO
total ← total + number
INPUT number
ENDWHILE
OUTPUT total

// REPEAT UNTIL — check AFTER at least one run
REPEAT
INPUT password
IF password <> "Secure1" THEN OUTPUT "Wrong"
ENDIF
UNTIL password = "Secure1"
Choosing the Right Loop

FOR vs WHILE vs REPEAT

FOR: use when the exact number of repetitions is known (e.g. process 30 students)
WHILE: use when condition checked first — loop may never run (e.g. only run if balance > 0)
REPEAT UNTIL: loop always runs at least once — condition checked after (e.g. must input at least once)
Key difference: WHILE may run 0 times; REPEAT UNTIL always runs at least 1 time
Exam Practice

Have a go at this question

Cambridge IGCSE 0478 style
Write pseudocode using a FOR loop to calculate and output the factorial of a number n (n! = 1 × 2 × 3 × … × n). Input n from the user.
4 marks
INPUT n
factorial ← 1
FOR i ← 1 TO n
factorial ← factorial * i
NEXT i
OUTPUT "Factorial = ", factorial
Key Takeaways

What to Remember

FOR...NEXT: count-controlled; use when number of iterations known before loop starts
WHILE...ENDWHILE: pre-condition check; may run zero times if condition false from start
REPEAT...UNTIL: post-condition check; always runs at least once before checking
STEP used in FOR loop to change increment: STEP 2 for odds, STEP -1 to count down