Skip to content

SpecificationVI · Control flow

6.5

The counted loop For

For counts from one number to another and runs the body once for each value, with a control variable that moves by itself.

Markdown version

6.5.1 How to write it

For «control» <- «inicial» To «final» ⟦Step «paso»⟧ Do
  «instrucciones»
EndFor

6.5.2 How it works

Before the first round, the initial value, the final value and the step are computed only once and in that order. Then, on every round:

  1. It checks whether the control has gone past the final value. The final value is included.
  2. If not, the body runs.
  3. The step is added to the control.

ProgramThe 7 times table

Algorithm Tabla
  For i <- 1 To 5 Do
    Write "7 x ", i, " = ", 7 * i;
  EndFor
EndAlgorithm

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

The program finishes normally.

  1. 11, 5 and the step 1 are computed. The control starts at 1.

  2. 2Every round writes a line and adds the step: 2, 3, 4…

  3. 3With the control at 5 the body still runs: the final value is included.

  4. 4The control reaches 6, which is past the final value. The loop ends.

Figure 6.5-1.The control walks the values from the initial one to the final one, both included. When it goes past the final value, the loop ends.

A line with the values 1 to 6. The control starts at 1 and moves one by one; 5, the final value, is still included; on reaching 6 the loop ends.

The direction depends only on the sign of the step. With a negative step it counts backwards. If the initial value is already past the final one, the body does not run:

ProgramNegative steps and empty loops

Algorithm Pasos
  For i <- 10 To 0 Step -5 Do
    Write i, " " Without Newline;
  EndFor
  Write "";
  For i <- 5 To 1 Do
    Write "nunca";
  EndFor
  Write "fin";
EndAlgorithm

Output

10 5 0 
fin

The program finishes normally.

The control variable lives only inside the loop. When it ends, it stops existing.

In short

  • For declares its control and moves it by itself.
  • Initial, final and step are computed once.
  • The final value is included; the sign of the step gives the direction.
  • A zero step is a failure; touching the control, an error.