When to Use WHILE, REPEAT...UNTIL and FOR Loops
Choose the right GCSE Computer Science loop: use FOR for a known count, WHILE to test before repeating, and REPEAT...UNTIL when code must run at least once.
Use a FOR loop when you know how many times to repeat. Use a WHILE loop when you need to check a condition before each repetition. Use a REPEAT...UNTIL loop when the instructions must run at least once, then continue until a condition becomes true.
A condition is a test that can be true or false. The key question is whether you know the number of repetitions in advance and when the test needs to happen.
Choosing a loop
A FOR loop is useful for a fixed number of repetitions. For example, if a program must ask five quiz questions, it can use a FOR loop to run the question-handling instructions five times.
A WHILE loop checks its condition before running the instructions each time. It keeps going while the condition is true. If the condition is false at the start, the instructions do not run at all. For example, a game might keep accepting moves while the player has lives remaining. If the player starts with no lives, it should not accept a move.
A REPEAT...UNTIL loop checks its condition after running the instructions. It always runs at least once and stops when the condition becomes true. For example, a program can ask for a password, then repeat the request until the correct password is entered: it needs to make the first request before it can check the answer.
Common exam mistake: WHILE and REPEAT...UNTIL usually describe opposite sides of the stopping test. “WHILE the password is incorrect” means keep going while that is true; “UNTIL the password is correct” means stop when that becomes true. Also check whether the instructions need to run at least once before choosing REPEAT...UNTIL.