Algorithmic I Ch 3: Conditional structures – 5) Sequential If Vs Nested if 2023-2024
Sequential If Vs Nested if
Problem : These three portions are supposed to display the sign of an integer number x, are
they correct ?
If (x˃0) then Print(ˮx is positiveˮ); Correct
Else If (x<0) then Print(ˮx is negativeˮ);
Else Print(ˮx is nullˮ);
Endif;
Endif;
If (x˃0) then Print(ˮx is positiveˮ); Endif; Correct
If (x<0) then Print(ˮx is negativeˮ);
Endif;
If (x=0) then Print(ˮx is nullˮ); Endif;
If (x˃0) then Print(ˮx is positiveˮ); Endif; Incorrect, beasause it display on the screen :
If (x<0) then Print(ˮx is negativeˮ); x is positive
Else Print(ˮx is nullˮ); x is null
Endif;
How many action blocks can be executed in each portion?
If ( Cond1) then
Block of Actions1;
Else
If (Cond2) then
Block of Actions2;
Else
If (Cond3) then
0 or 1 blocks only
Block of Actions3;
Endif;
Endif;
Endif;
If ( Cond1) then
Block of Actions1;
Endif;
If (Cond2) then
Endif;
Block of Actions2; 0, 1, 2, or 3 blocks
If (Cond3) then
Block of Actions3;
Endif;
Conclusion :
We use nested If .. Else .. Endif; when you are in a situation where a single block of
actions can be executed among several, Example: display the sign of an integer,
display the state of water, etc.…
We use sequential If .. Endif; when you are in a situation where one or more blocks of
actions can be executed, Example: display all the errors of a given date…
Page 1 sur 1