Back

Nesting

Nested IF-THEN-ELSE-ENDIF
Not only can you make selections using the IF construct, you can also put them inside each other!  When we do this, we say that the IF instructions are nested. Nesting is a very useful technique so long as the code is laid out correctly and you don’t use too many nested IF statements. Consider this example that uses nested IF statements.

INPUT ExamMark
IF (ExamMark < 40) THEN
      PRINT "You have failed."
ELSE
      IF (ExamMark < 60) THEN
           PRINT "You have passed."
      ELSE
           IF (ExamMark  < 70) THEN
                PRINT "You have passed with a merit."
           ELSE
                IF (ExamMark <80) THEN
                     PRINT "You have passed with a distinction."
                ELSE
                     PRINT "Outstanding! You have passed with honours!"
                ENDIF
           ENDIF
      ENDIF
ENDIF

Nested iteration
You can nest any combination of iterative constructs as well. Have a look at this pseudo-code program:

Declare Num1, Num2, Multiplier, Answer, Counter As Integer

Multipler = 2
Num1 = 1
Num2 = 10

Do While Multiplier < 4
      For Counter = Num1 to Num2
          Answer = Counter * Multiplier

          Add_to_the_display: Counter & "Times" & Multiplier & " = " & Answer
    Next Counter
     Multiplier = Mulitplier + 1
Loop

You can see in this example that there is a For loop inside a While loop. To put this another way, we have one iterative construction inside another one. They are 'nested'.

Back