Loop structures: Difference between revisions
Content added Content deleted
(→Factor) |
(→Forth) |
||
Line 267: | Line 267: | ||
==[[Forth]]== |
==[[Forth]]== |
||
===DO-LOOP=== |
===DO-LOOP=== |
||
<syntaxhighlight lang="forth"> |
|||
⚫ | |||
( limit start ) DO ( iterated statements ) 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 |
example: Two standard iterations |
||
<syntaxhighlight lang="forth"> |
|||
⚫ | |||
10 0 DO I . LOOP \ Prints the numbers from 0 to 9 |
|||
⚫ | |||
</syntaxhighlight> |
|||
===BEGIN-UNTIL=== |
===BEGIN-UNTIL=== |
||
<syntaxhighlight lang="forth"> |
|||
BEGIN ( iterated statements ) ( conditional ) UNTIL |
|||
</syntaxhighlight> |
|||
example: Counts down from a given number to zero |
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=== |
===BEGIN-AGAIN=== |
||
<syntaxhighlight lang="forth"> |
|||
BEGIN ( iterated statements ) AGAIN |
|||
</syntaxhighlight> |
|||
example: echo user's input |
example: echo user's input |
||
<syntaxhighlight lang="forth"> |
|||
: FOREVER ( -- ) BEGIN KEY EMIT AGAIN ; |
|||
</syntaxhighlight> |
|||
===BEGIN-WHILE-REPEAT=== |
===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 |
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. |
Additional WHILE clauses may be added to a loop, but each extra WHILE requires a matching THEN after the REPEAT. |
||
Line 295: | Line 312: | ||
A good example of a useful combination is this complex loop: |
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 |
|||
⚫ | |||
</syntaxhighlight> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
<syntaxhighlight lang="forth"> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
</syntaxhighlight> |
|||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |