Jump to content

Loop structures: Difference between revisions

Line 267:
==[[Forth]]==
===DO-LOOP===
<syntaxhighlight lang="forth">
( limit start ) DO ( iterated statements ) LOOP
( limit start ) DO ( iterated statements ) ( increment ) +LOOP
( limit start ) DO ( iterated statements ) ( increment ) +LOOP
LEAVE \ exits a DO loop
UNLOOP EXIT \ cleans up loop counters from return stack before returning from the current word
</syntaxhighlight>
 
example: Two standard iterations
<syntaxhighlight lang="forth">
10 0 DO I . LOOP \ Prints the numbers from 0 to 9
10 0 DO I . 2 +LOOP \ Prints the even numbers from 0 to 89
10 0 DO I . 2 +LOOP \ Prints the even numbers from 0 to 98
</syntaxhighlight>
 
===BEGIN-UNTIL===
<syntaxhighlight lang="forth">
BEGIN ( iterated statements ) ( conditional ) UNTIL
</syntaxhighlight>
 
example: Counts down from a given number to zero
<syntaxhighlight lang="forth">
: COUNTDOWN ( n -- ) BEGIN DUP CR . 1- DUP 0< UNTIL DROP ;
</syntaxhighlight>
 
===BEGIN-AGAIN===
<syntaxhighlight lang="forth">
BEGIN ( iterated statements ) AGAIN
</syntaxhighlight>
 
example: echo user's input
<syntaxhighlight lang="forth">
: FOREVER ( -- ) BEGIN KEY EMIT AGAIN ;
</syntaxhighlight>
 
===BEGIN-WHILE-REPEAT===
<syntaxhighlight lang="forth">
BEGIN ( unconditional iterated statements ) ( conditional ) WHILE ( conditional iterated statements ) REPEAT
example: counts down from a given number to one
: COUNTDOWN ( n -- ) BEGIN DUP WHILE CR DUP . 1- REPEAT DROP ;
</syntaxhighlight>
Additional WHILE clauses may be added to a loop, but each extra WHILE requires a matching THEN after the REPEAT.
 
Line 295 ⟶ 312:
 
A good example of a useful combination is this complex loop:
<syntaxhighlight lang="forth">
BEGIN
( condition 1 )
WHILE
( condition 2 )
UNTIL
( condition 2 succeeded )
ELSE
( condition 1 failed )
THEN
An example of using this idiom in practice might be this pseudo-Forth
</syntaxhighlight>
BEGIN
read-next-record
WHILE
found-record
UNTIL
process-record
ELSE
error" Ran out of records looking for the right one!"
THEN
 
An example of using this idiom in practice might be this pseudo-Forth
<syntaxhighlight lang="forth">
BEGIN
read-next-record
WHILE
found-record
UNTIL
process-record
ELSE
error" Ran out of records looking for the right one!"
THEN
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.