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 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.
Example.
To add the even numbers less than 100, you can start by setting the
running total to 0:
Input:
then use a for loop to do the summing:
Input:
Output:
2450 |
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:
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:
then use the second form of the for loop to do the summing:
Input:
or (a French version of this syntax):
Output:
2450 |
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:
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:
then use the third form of the for loop to add the integers:
Input:
or:
Output:
5050 |