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
Q1. There are four IF-THEN-ELSE-ENDIF constructs in the code above. Using 4 coloured pens, identify the four constructs, making sure that you work out which IF, THEN, ELSE and ENDIF belong together!
Q2. Follow the above code when you input these numbers: a) 25 b) 40 c) 57 d) 61 e) 75 f) 90. Write down the output in each case. Be very clear what happens once a PRINT statement has been done. You need to ensure that you have done
task 1 above so that you can identify the components of the four IF constructs.
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
L
oop
Q3. What does the above program do?
Q4. Can you work out what will be displayed in the above example?
Q5. Use a trace table and dry run the program. Some help can be found here.
|