Iteration: FOR
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
FOR counts
- A count-controlled loop runs once for each integer from the start to the end, inclusive.
- The counter is an
INTEGER. - It is good practice to repeat the counter's name after
NEXT.
DECLARE Total : INTEGER
Total ← 0
FOR I ← 1 TO 5
Total ← Total + I
NEXT I
OUTPUT Total
Explore
Trace the running total
A FOR loop repeats a set number of times. Step through and watch Total grow.
STEP changes the jump
STEPsets the gap between values. It can be negative.- If the start is already past the end in the step's direction, the body does not run.
FOR I ← 5 TO 1 STEP -2
OUTPUT I
NEXT I
Watch out
NEXT Imust name the counter of this loop.- The body is indented.
NEXTlines up withFOR.
Common mistakes
1 TO 5includes both 1 and 5.- Do not change the counter yourself inside the body.
Now you try
- Use a
FORloop to print a run of numbers.
Use a FOR loop to output the numbers 1 to 5, one per line.
Click Run to see the output here.
Output 5, 3 and 1, using FOR with STEP -2.
Click Run to see the output here.