While

The "while" control structure is the combination of a loop and "if" statement.

while condition
... instructions ...
/while

Example of while int x = 10

while x < 20
  echo x, " "
  x + 1
/while
Displays: > 10 11 12 13 14 15 16 17 18 19



Along with while, we have to introduce two special instructions that are useful with any loop.

Break

This command exits the loop.
The example below uses the "forever" keyword that creates an infinite loop.

Example of break int x = 0

while forever
  print x
  if x > 100 break
  x + 1
/while



When the 100 value is reached by x the break statement skips the end of the loop and exits the structure to execute following statements.

Continue

This command skip all following statement inside the while structure and jumps at the /while marker, thus starts a new loop.

Example of continue int x = -1

while x < 20
  x + 1
  if (x mod 2) = 0 continue
  print x
/while



 This program displays only odd values for x, because when even values are encountered, the condition is matched and the continue statement executed.
 In this example, the increment of x must be on the first line in the structure.
You know the reason if you have already programmed. Suppose x is incremented on the last line, as in previous examples, the continue statement would had created an infinit loop as the incrementing is skipped and x remains on an odd value forever.
To avoid the risk of infinite loop, an option exists in Scriptol.

While let

This variant avoid infinite loops in the while statement, as the let command allows to move the incrementing outside the part of the bloc that is skipped by the continue command.


Example of while ... let int x = 0

while x < 20
  if (x mod 2) = 0 continue
  print x
/while let x + 1


That is the conventional form. A simpler one exists, it is recommanded each time a while condition depends upon the value of a counter incremented or decremented at end of the bloc of statements.


Example of the simpler while ... let
int x = 0

while x < 20
  if (x mod 2) = 0 continue
  print x
let x + 1


 Exercises
1) In the line of the examples above, display odd numbers from 1 to 9.

Answer