Control Structures

begin until
BEGIN UNTIL loops check a condition flag at the end of the loop. : toZero ( n --, print n to 1 or 0 ) BEGIN dup. 1- dup 0> UNTIL drop

do loop
The DO word takes two numbers off of the stack. The top number is the base value for the loop counter variable, accessed by I, while the next number down is the limit. I will equal the base value to the limit-1. The following prints out the numbers 0 to 9 or the numbers 1 to 10 depending on implementation. : printNums ( -- ) 10 0 DO     I. LOOP

begin while repeat
BEGIN WHILE REPEAT loops allow a condition to be tested before executing the loop. : factorial ( n -- n! ) 1   BEGIN over dup 0> WHILE * swap 1+ swap REPEAT drop swap drop

if then
The IF word requires a boolean flag at the top of the stack and pulls the value off of the stack in the process. If true (non-zero), the statements up to the paired THEN word are executed. : maybeDivide ( n m -- n n/m ) dup 0= not if     over swap / then

if else then
Splitting a pair of IF THEN words with an ELSE causes the half before the ELSE to be executed if true and the half after the ELSE to be executed if false. : factorial ( n -- n! ) dup 0= if     drop 1 else 1+ 1 swap 0 do       I * loop then

switch
Uses a series of nested if else then blocks to check limited ranges. dup 0 > if dup 1 > if dup 2 > if dup 3 > if \ 4 or more else \ 3 then else \ 2 then else \ 1 then else \ 0 or less then