The for structure

We go back to lists with the for loop, the goal of which being to set one by one into a variable, each element of a list or a range of values.

The syntax is :

 for declaration in (identifier | interval)
        (instructions)*
 /for

That means for:
- for a variable x, scanning the identifier or the interval,
- zéro, one or several instructions,
- end of structure (and next element pointed out).

Example, we have an array "a".

 for text t in a
        ... instructions ... 
 /for 

The for loop can contains other control structures.

Embedding for: for text t in a
  for int
i in 1..3
    print t, i
  /for
/for

  
For structure on a single line

The compiler recognizes the end of the heading by the end of line. An instruction may be put also on the line providing the heading is terminated by a colon ":".

 for text t in a :  print t 
 /for 

The /for may be put also on the same line, providing a single instruction is in the bloc and it is terminated by a semi-colon.

 for text in a : print t; /for 

These conventions concern also if and all other control structures.

Using for on an interval. array a = array()
for int
i in 1..3
  a[i] = i
/for

a.display()
Displays: > array (
   1,
   2,
   3
)


 Exercises

 

1) Fill an array named "alphabet" with letters of the alphabet.
Use these builtins functions:
- int ord(text): converts a lettre (text format) into number.
- text chr(int): converts a number into text.
Display the array with the display() method.


Answer