Control structures
    Il "Quarto" fuso ] The 4th Time Zone ]   


 

Introduction
Input/Output operations
Mathematical Operators
Stack operators
Other operators
Colon definition
Control structures
Conditional branching
Constants and variables
Other Forth words
Using the editor
Error messages


                                   

[ Index ][ Back ][ Next ]

LOOPS

There are essentially two forms of loop operation

(1)                DO LOOP

(2)                DO +LOOP

The first loop structure is used as follow:

limit  start  DO  forth-words +LOOP

The ‘forth-words’ within the loop are executed until start equals to limit, incrementing the start (or index) by one each time.

Type:

: TEST1 5 0 DO ." Forth " CR LOOP ; <CR>

typing in

TEST <CR>

will print

Forth
Forth
Forth
Forth
Forth

The second loop structure is used as follow:

limit  start  DO    forth-words    increment  +LOOP

The ‘forth-words’ within the loop are executed from start to limit with the index being incremented or decremented by the value increment.

Try:

: TEST2 5 0 DO ." Hello! " CR 2 +LOOP ; <CR>

executing TEST2 will print

Hello!
Hello!
Hello!

Since the limit and index are held on the return-stack, it would be useful if we could examine the index. Well, there are words to do this:

I

This will copy the loop index from the return stack onto the data stack.

J

This will push the value of the nested LOOP index to the stack.

K

This will push the value of the double nested LOOP index to the stack.

Type:

: TEST3
4 0 DO 4 0 DO 4 0 DO  <CR>
  I J K . . . CR      <CR>
LOOP LOOP LOOP ;      <CR>

executing TEST3 will print

111
112
113
...

and so on.

[ Index ][ Back ][ Next ]


Ultimo aggiornamento: 10-12-2002. Copyright (c) 2000-2002 Matteo Vitturi. 
Per problemi o domande relativamente a questo sito contattare il webmaster
Last update: 12.10.2002. Copyright (c) 2000-2002 Matteo Vitturi.
For problems or questions related to this web please contact the webmaster.
1