Do while, do until, do case
If you want to perform a processing inside a loop at least one time, you have to move the test of the condition to the end of the loop with the while keyword...Example of do ... while control structure: |
int
x = 0 do print x x + 1 /do while x < 3 |
Displays: | >
0 > 1 > 2 |
Here also the forever keyword may be used along with a break
command.
Do until
And if you perform a loop until a condition is reached (and not while it
is true), then use the until variant instead.
Example displaying x until its value is 10: | int
x = 0 do print x x + 1 until x = 3 |
Affiche: | >
0 > 1 > 2 > 3 |
Maybe you wonder why one have to write simply until here, and "/do
while" above. There is a reason in the compilation process: as while
may begin another control structure, the compiler would be confused, that
is not the case with until.
(Take note that /do until works perfectly also.)
Do case
The content of a "do" statement may be splitted into several conditional
cases among which one is selected and processed.
The body of a do structure may be divided into several conditional cases,
and a single one is selected by the computer and executed.
No any symbol is required at the end of a case block.
Example of a do ... case control structure. |
do case name = "pussycat": print "this is a cat" case name = "flipper": print "this ia a dolphin" case name = "mobby dick": print "this is a whale" else print "this is another animal" /do |
The "while condition" has disappeared here, but one can keep it if needed, this will result just in a finite-state automata!
To complete a such automata, one need for some no conditional processing inside the structure, and that is allowed by the always option.
Example of do ..case while, structure making a finite-state automata. | int
state = ON do case state = ON: counter + 1 case state = OFF: break always state = getState() ` some function /do while forever |
We have just designed a kind of automata that gets its state from some function, here named getState(), and the automate continues to work until the OFF state is encountered.
Exercises |
1) Display the odd numbers from 0 to 10 by using the i variable and
do until. |