Previous Up Next

12.3.3  The for loop: for from to step do end_for

The for loop has three different forms, each of which uses an index variable. If the for loop is used in a program, the index variable should be declared as a local variable. (Recall that i represents the imaginary unit, and so cannot be used as the index.)

The first form:

For the first form, the for is followed by the starting value for the index, the end condition, and the increment step, separated by semicolons and in parentheses. Afterwards is a block of code to be executed for each iteration:

for (j:=j0; end_cond; increment_step) block

where j is the index and j0 is the starting value of j.


Example.
To add the even numbers less than 100, you can start by setting the running total to 0:
Input:

S:= 0

then use a for loop to do the summing:
Input:

for (j:= 0; j < 100; j:= j + 2) {S:= S + j}

Output:

2450


The second form:

The second form of a for loop has a fixed increment for the index. It is written out with for followed by the index, followed by from, the initial value, to, the ending value, step, the size of the increment, and finally the statements to be executed between do and end_for:

for j from j0 to jmax step k do statements end_for

where j is the index, j0 is the initial value of j, jmax is the ending value of j, k is the step size of j, and statements are executed for each value of j.


Example.
Again, to add the even numbers less than 100, you can start by setting the running total to 0:
Input:

S:= 0

then use the second form of the for loop to do the summing:
Input:

for j from 2 to 98 step 2 do S:= S + j; end_for

or (a French version of this syntax):

pour j de 2 jusque 98 pas 2 faire S:= S + j; fpour

Output:

2450


The third form:

The third form of the for loop lets you iterate over the values in a list (or a set or a range). In this form, the for is followed by the index, then in, the list, and then the instructions between do and end_for:

for j in L do statements end_for

where j is the index and L is the list to iterate over.


Example.
To add all integers from 1 to 100, you can again set the running total S to 0:
Input:

S:=0

then use the third form of the for loop to add the integers:
Input:

for j in 1..100 do S:= S + j; end_for

or:

pour j in 1..100 faire S:= S + j; fpour

Output:

5050

Previous Up Next