Level 0, lesson 21

# 0.21 WHILE-DO constructs

A WHILE-DO construction is a construction that will perform zero or more iterations. First a condition is checked, then the body is executed. Then it will branch back to the condition. In 4tH it looks like this:

         BEGIN <condition> WHILE <body> REPEAT

The condition will have to evaluate to TRUE in order to execute the body. If it evaluates to FALSE it branches to just after the REPEAT. This example does a Fibbonaci test.

         : fib 0 1
               begin
                    dup >r rot dup r> >       \ condition
               while
                    rot rot dup rot + dup .   \ body
               repeat
               drop drop drop ;               \ after loop is executed

You might not understand all of the commands, but we'll get to that. If you enter "20 fib" you will get:

         1 2 3 5 8 13 21

This construct is particularly handy if you are not sure that all data will pass the condition.