A loop has three boundaries to get right: where it starts, where it stops and how much it changes each pass. Work these out from the question before you write the loop, not after you see the output.
This lesson is part of programming foundations. The skill of tracing loops is covered separately in writing a trace table that exposes an off-by-one error.
How do you count the passes?
For a FOR loop, the number of passes is last − first + 1. The plus one counts both ends.
| Loop | Calculation | Passes |
|---|---|---|
| FOR i = 1 TO 10 | 10 − 1 + 1 | 10 |
| FOR i = 3 TO 11 | 11 − 3 + 1 | 9 |
| FOR i = 0 TO 10 | 10 − 0 + 1 | 11 |
Decide the pass count from the question first. Then pick the boundaries that give exactly that count.
Worked example: multiples of five
The task is to print the first ten multiples of 5, which are 5, 10, up to 50.
FOR i = 1 TO 10
OUTPUT i * 5
NEXT i
The loop runs 10 − 1 + 1 = 10 times. On pass 1 it prints 5, and on pass 10 it prints 50. That matches the task exactly.
What goes wrong with the wrong start?
A student who habitually starts counting at zero writes FOR i = 0 TO 10. The loop now runs 11 times.
| Version | First output | Last output | Count |
|---|---|---|---|
| FOR i = 0 TO 10 | 0 | 50 | 11 |
| FOR i = 1 TO 10 | 5 | 50 | 10 |
The extra first line prints 0, which is not a multiple the task asked for. The fix is to start at 1, or to keep 0 and end at 9 while printing (i + 1) * 5. The first is simpler.
How does a WHILE loop differ?
A WHILE loop has no counter built in, so you must create one. You set the start before the loop, test the boundary in the condition, and update inside.
The safest check is to ask three things: does the variable start correctly, does the condition include the last wanted value, and does the body change the variable toward the stop? Miss the third and the loop never ends.
Check yourself
Write a loop that prints 3, 6, 9 and so on up to 30. How many passes does it run?
Answer
FOR i = 1 TO 10
OUTPUT i * 3
NEXT i
The last value 30 = 10 × 3, so i runs from 1 to 10. The passes are 10 − 1 + 1 = 10.
What to study next
Next, follow values through a function call in tracing functions and parameters. To practise loop tracing on your own device, use the restricted pseudocode trace trainer.
If you want a teacher to check your loop limits on new questions, see online one-to-one Computer Science tuition.