Exercises - combining loops – IBM SC34-5764-01 User Manual

Page 69

Advertising
background image

DO outer = 1 TO 2

DO inner = 1 TO 2

SAY 'HIP'

END
SAY 'HURRAH'

END

The output from this example is:

HIP
HIP
HURRAH
HIP
HIP
HURRAH

If you need to leave a loop when a certain condition arises, use the LEAVE instruction followed by the
name of the control variable of the loop. If the LEAVE instruction is for the inner loop, processing leaves
the inner loop and goes to the outer loop. If the LEAVE instruction is for the outer loop, processing leaves
both loops.

To leave the inner loop in the preceding example, add an IF...THEN...ELSE instruction that includes a
LEAVE instruction after the IF instruction.

DO outer = 1 TO 2

DO inner = 1 TO 2

IF inner > 1 THEN

LEAVE inner

ELSE

SAY 'HIP'

END
SAY 'HURRAH'

END

The result is as follows:

HIP
HURRAH
HIP
HURRAH

Exercises - Combining Loops

1. What happens when the following program runs?

DO outer = 1 TO 3

SAY

/* Produces a blank line */

DO inner = 1 TO 3

SAY 'Outer' outer 'Inner' inner

END

END

2. Now what happens when the LEAVE instruction is added?

DO outer = 1 TO 3

SAY

/* Produces a blank line */

DO inner = 1 TO 3

IF inner = 2 THEN

LEAVE inner

ELSE

SAY 'Outer' outer 'Inner' inner

END

END

ANSWERS

1. When this example runs, it produces the following:

Control Flow within a Program

Chapter 4. Controlling the Flow within a program

47

Advertising