# For loops

When using a for loop you can define how many times the loop will be repeated. This is very useful for all kinds of scenarios, for example, if a level has 10 enemies you can use a for loop to cycle through those 10 enemies to control their behaviour.

This example shows how a for loop can be used. Try running the program. You will see the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 displayed on screen.

    do
    	for i = 1 to 10
    		print ( i )
    	next i

    	sync ( )
    loop

A for loop works by requiring a variable to be used to control how many times the loop will run. In our example program this is handled by declaring a variable i, assigning it a value of 1 and then setting the end point to 10. All of this takes place on the same line. The code immediately following the for loop will be executed every time the loop runs. The final part of the loop uses the next keyword to tell the program to iterate the variable i. When the program reaches this stage it will look at the variable i, add 1 to it, then return to the start of the for. If the variable i is less than the end condition (10), then the loop can continue, otherwise the loop is finished and the code within it is not executed, meaning program control moves onto the next line, which in our case is a call to the sync command.

Literal numbers have been used in the example. These can be replaced by any kind of expression. The point to remember here is that a start and end point need to be specified for the loop and bear in mind that by default the variable is incremented by 1 each cycle of the loop.

The step keyword can be used to control the increment for the variable. This is useful in cases where you don't want the variable controlling the start and end point to automatically increment by 1 each loop. Here's how the step keyword can be used.

    do
    	for i = 1 to 10 step 2
    		print ( i )
    	next i

    	sync ( )
    loop

Instead of i incrementing by 1 each loop, it is now set to increment by 2. As a result of this the end point of the loop is going to be reached quicker. It will only run through the loop 5 times, displaying the numbers 1, 3, 5, 7 and 9 on screen.

The step keyword also accepts negative numbers, so a loop could be set up to count backwards, as shown in this example.

    do
    	for i = 10 to 1 step -1
    		print ( i )
    	next i

    	sync ( )
    loop

These numbers will be displayed on screen 10, 9, 8, 7, 6, 5, 4, 3, 2 and 1. Notice how the start point of the loop is a higher number than the end point. This needs to be the case as we're now moving backwards.