Iteration: FOR
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
FOR repeats a fixed number of times
- A
FORloop counts from a start value to an end value. NEXTmarks the end of the loop body.
FOR i ← 1 TO 5
OUTPUT i // 1, 2, 3, 4, 5
NEXT i
A running total
- Start a total at 0, then add to it inside the loop.
Total ← 0
FOR i ← 1 TO 10
Total ← Total + i
NEXT i
OUTPUT Total // → 55
Explore
Trace the running total
A FOR loop repeats a set number of times. Step through and watch Total grow.
STEP changes the count
STEPsets how much the counter changes each pass.STEP -1counts down.
FOR i ← 5 TO 1 STEP -1
OUTPUT i // 5, 4, 3, 2, 1
NEXT i
Watch out
- Use
FORwhen you know how many times to repeat; useWHILEwhen you do not. - The counter (
i) andNEXT imust use the same name.
Common mistakes
FOR i ← 1 TO n ... NEXT irunsntimes, including both ends.- The counter changes automatically each turn.
Now you try
- Use
FOR ... NEXT. Type<-for←. - Press Check answer to test it.
Use a FOR loop to output the numbers 1 to 5, one per line.
Click Run to see the output here.
Use a FOR loop to add up 1 to 10, then output the total (it is 55).
Click Run to see the output here.
Read an INTEGER N, then output N × 1, N × 2, N × 3 (one per line). For input 4, output 4, 8, 12.
Click Run to see the output here.