If - then - else

If - then - else

Top  Previous  Next

A characteristic that makes programs seem intelligent is the ability to select alternative courses of action. The "if" statement enables alternatives to be selected based on a condition.

 

The "if" statement has two forms:

 

        if BOOLEAN EXPRESSION then STATEMENT

        if BOOLEAN EXPRESSION then STATEMENT else STATEMENT

 

The "if" statement is used to execute statements or blocks of code conditionally. For example:

 

        if Number = Guess then Correct:= true else Correct:= false

 

This statement tests to see if Number is equal to Guess. If it is equal, the variable Correct gets the value "true"; if it is not equal then Correct gets "false".

 

Usually the condition is based on a comparison, but any expression that evaluates to true or false can be used. Here are some examples:

 

        if A/B+C-D = (Time+1)/45 then Pig:= true;

        if Pig then [X:= 3;  Y:= 4] else [X:= 4;  Y:= 3];

        if A=B & C=D then Frog:= 1 else Frog:= 0

 

Two of the examples shown in this section can be simplified:

 

        Correct:= Number = Guess;

        Frog:= if A=B & C=D then 1 else 0

 

The first simplification is an often overlooked use of boolean expressions. The second simplification uses an "if" expression instead of an "if" statement. Note the difference between the two uses of "if".