Previous Up Next

25.3.3  For loop

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 keyword 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, where j is the index and j0 is the starting value of j:

for (j:=j0end_condincrement_step) block

Example

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

S:=0

Then use a for loop to do the summation:

for (j:=0;j<100;j:=j+2) { S:=S+j }
     
2450           
The second form.

The second form of a for-loop has a fixed increment for the index. It is written out with the for keyword followed by the index, then 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:

S:=0

then use the second form of the for loop to do the summation:

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
     
2450           
The third form.

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

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:

S:=0

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

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

or:

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

Previous Up Next