Conditionals I

Useful programs make decisions. Words to do this are known as conditionals.

The simplest conditionals are the pair IF ... THEN. An example:

		:  two?  2 = IF  "Yes, this is two! :)" . cr THEN ;
	

We can test the word TWO?

		3 two? 
		ok
		2 two? 
		Yes, this is two! :) ok
	
Understand how this works:
  1. IF reads the top of the stack.
  2. If the item is
    true
    , then the stuff between
    IF
    and
    THEN
    is executed.
  3. If the item is
    false
    , then execution continues after
    THEN
    .

ELSE

We can easily extend our program to include a dire warning if the value isn't 2:

			:  two?  
			    2 = IF  
			    	"Yes, this is two! :)" 
			    ELSE  
			    	"No, this is not two. :(" 
			    THEN . cr
			;
		
Understand how this works:
  1. IF reads the top of the stack.
  2. If the item is
    true
    , then the stuff between
    IF
    and
    ELSE
    is executed.
  3. If the item is
    false
    , then the stuff between
    ELSE
    and
    THEN
    is executed.
  4. Then execution continues after
    THEN
    .

Quiz

Question 1

Notice that I have slightly re-arranged the dot and
CR
after
THEN
. Why did I do this?



Question 2

Can you use
IF
,
ELSE
and
THEN
in interpretation mode? Test out your answer.



Question 3

Write a word
EVEN?
which prints out "yay" if the value on the stack is even and "nay" if it is not. Make use of integer modulus,
MOD
(see the Math section).



Next: Conditionals II