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.)
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:
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 } |
|
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:
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.
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 |
|
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:
where j is the index and L is the list to iterate over.
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 |
|