Other Looping Constructs
The other useful Smojo looping constructs areBEGIN,
UNTILand
AGAIN.
Example 1
This loop will never terminate: never-ending begin "hi" . cr again ;
Example 2
UseUNTILif you need to check for a condition to terminate
: 5count 0 begin 1+ dup . dup 5 > until ; 5count 1 2 3 4 5 6 ok
Example 3
You can also useWHILE-REPEATloops
: 4chan 0 begin 1+ dup 5 < while "Ho!" . repeat ; 4chan Ho! Ho! Ho! Ho! ok
Quiz
Question 1
Rewrite4CHANusing
BEGIN,
AGAINand
EXIT.
: 4chan 0 begin 1+ dup 5 = if exit then "Ho!" . again ; 4chan
Question 2
Write a wordSQUARESwhich prints all the square numbers which are less then 1000 using the looping constructs above.
: squares 0 begin 1+ dup 2 ^ dup 1000 < while . repeat ; squares
Question 3
Write a wordTRIANGLE9which prints the following.
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9
: triangle9 0 begin 1+ dup 0 do dup . loop cr dup 9 = until ; triangle9