With a For loop, you can execute a statement or block of statements for a specified number of times.

For this kind of loop, you need a numeric counter variable (that you of course have to define in the declaration section of your program). This variable tracks how often the loop was already executed. When you start the loop, you assign a starting value to this variable. The value of the variable is then automatically incremented by one (if you use the keyword To) or decremented by one (if you use Downto) each time the loop is executed.

Tip The counter variable is often called i or j.

When the value of the counter variable reaches the stop value that you define in the To or Downto part of the loop, the loop is broken and the program is executed from the next statement after the loop. To make sure that the counter value always reaches the stop value, use the keyword To when the stop value is higher than the start value, and use Downto when the stop value is lower than the start value.


For Variable = StartValue To StopValue Do


Starts the For loop

Variable = StartValue

Assigns a starting value to the counter variable


(or Downto)

Starts the To control block that determines when the loop will end

Use the keyword Downto instead it your stop value is lower than the start value


Sets the stop value that must be reached by the counter variable to break the loop


Starts the Do execution block that is executed several times until the stop value is reached


Any command statement or block statement that will be executed as long as the stop value is not met


A hypothetical For loop that draws five identical Moving Averages on the screen:

For counter=0 To 5 Do
DrawLine("MovS" + counter, Result);

You can also use the counter variable inside the loop here it is used to determine which element is added to the result (during the execution of the loop, all elements up to the value of period will be added):

For i=0 To period Do
Result = Result + source[i];