A for loop is a form of iteration, often used as an alternative to a while loop.
Quite often, we need to loop for a specific number of times. For example, if you wanted to print the 7 times table you would need to loop 12 times.
You can do this with a while loop and a counter variable, but you end up writing similar code every time you want to do this type of loop. It is such a common thing to do that most languages have a special way of doing it - the for loop.
A for loop looks something like this:
FOR i = 0 TO 4 PRINT(i) ENDFOR
The first line declares a variable i, and sets the loop to run from 0 to 4. So the loop will print:
0 1 2 3 4
The first number is called the start value (or initial value), and the second number if called the end value.
{{% orange-note %}} Different languages have different ways of defining a for loop. Often, as shown, the loop count starts at 0. If we want the loop to execute n times, it will count from 0 to n - 1. {{% /orange-note %}}
Of course, you can use variables for the start and end values:
FOR i = a TO b PRINT(i) ENDFOR
where a and b are variables that have been initialised in code before the start of the loop.
By default the loop counters changes by 1 each time. A step value allows the loop count to change by a different value:
FOR i = 0 TO 4 STEP 2 PRINT(i) ENDFOR
Starting at 0, the variable i steps by 2 each time until it reaches 4. This prints:
0 2 4
The step can be negative, causing the loop to count down:
FOR i = 10 TO 5 STEP -1 PRINT(i) ENDFOR
This prints:
10 9 8 7 6 5
Copyright (c) Axlesoft Ltd 2021