Do Loops
The power of computers is that they don't get tired of doing the same thing again and again.
The pair DO ... LOOP are words to automate such repetition. For example, this program:
: counter 0 DO i . LOOP ; 5 counterwill produce the result:
0 1 2 3 4 ok
DOexpects 2 items on the stack: the end and start of the loop index. In the example above, what is the start index? What is the end index? The word
Ipushes the current value of the loop index onto the stack.
Important Points
- You cannot use
DO...LOOP
in interpretation mode. You can only use it in compilation mode, i.e., inside a word definition.
- If the end index is less than the start index in a DO loop, the loop never stops. For example:
0 5 DO...LOOP
will never end, and you will be kept waiting for the result. - Never amend the return stack inside a
DO...LOOP
, because the loop stores/uses items (eg, the current loop index) on the return stack.
Quiz
Question 1
Amend the program so that it prints numbers from 0 to 15.
: counter 0 DO i . LOOP ; 16 counter \ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Question 2
AmendCOUNTERso that it prints numbers starting from 1 instead of 0.
\ count from 1 : counter 1 DO i . LOOP ; 5 counter \ 1 2 3 4
Question 3
How to print the end index also, instead of stopping short of it?
\ include end : counter 1 + 0 DO i . LOOP ; 5 counter \ 0 1 2 3 4 5
Question 4
AmendCOUNTERso that it prints three times the value of the loop index.
: counter 0 DO i 3 * . LOOP ; 5 counter \ 0 3 6 9 12
Test all your answers before continuing.