Code examples help you learn how to specify IF…THEN…ELSE
instructions.
Sometimes it is necessary to have one or more IF…THEN…ELSE instructions within other
IF…THEN…ELSE instructions. Having one type of instruction within another is called
nesting. With nested IF instructions, it is important to match each IF with an ELSE and each DO with
an END.
IF weather = fine THEN
DO
SAY 'What a lovely day!'
IF tenniscourt = free THEN
SAY 'Let''s play tennis!'
ELSE NOP
END
ELSE
SAY 'We should take our raincoats!'
Not matching nested IFs to ELSEs and DOs to ENDs can have some surprising results. If you
eliminate the DOs and ENDs and the ELSE NOP, as in the following example, what is the outcome? Figure 1. Example of Missing Instructions
/******************************** REXX *******************************/
/* This program demonstrates what can happen when you do not include */
/* DOs, ENDs, and ELSEs in nested IF...THEN...ELSE instructions. */
/*********************************************************************/
weather = 'fine'
tenniscourt = 'occupied'
IF weather = 'fine' THEN
SAY 'What a lovely day!'
IF tenniscourt = 'free' THEN
SAY 'Let''s play tennis!'
ELSE
SAY 'We should take our raincoats!'
Looking at the program, you might assume the ELSE belongs to the first IF. However, the
language processor associates an ELSE with the nearest unpaired IF. The outcome is as follows:
What a lovely day!
We should take our raincoats!
Exercise:
using the IF…THEN…ELSE
instruction
Write
the REXX instructions for the following flowchart:
ANSWER
IF a = 0 THEN
IF c = 2 THEN
z = 1
ELSE NOP
ELSE
IF z = 2 THEN
IF c = 3 THEN
a = 1
ELSE
a = 3
ELSE NOP