Embedded IF-ELSE structures
Graphically, IF-ELSE structures may be visualized as railway switches: it opens way to one of two different paths of instructions depending on a condition’s value. There are however situations where two paths are not enough. For instance, an algorithm establishing the state of water according to its temperature may have to choose among three possible answers (solid, liquid or gaseous).
A first solution would be the following:
WRITE "Temperature of
The above pseudo-code is rather laborious. Conditions are more or less alike, and the flow of execution must examine three successive conditions all on the same topic, the temperature (i.e. the value of variable Temp). It would be more rational to embed the conditional structures one within the other:
WRITE " Temperature of
This new pseudo-code saves on the
amount of source code: instead of having three conditions, we only have two
simple. Furthermore, we made savings in terms of execution time on the new
algorithm: if the temperature is less than zero, the algorithm writes « It’s
ice » and the flow of execution jumps directly after the last ENDIF,
without examining the other possibilities (which are evidently false).
This second version of the algorithm produces exactly the same results as the previous pseudo-code, but more efficiently and in a more concise way. Embedded conditional structures are therefore an elegant and efficient approach to simplify and optimize algorithms.
Conditional structures may also be embedded in flowcharts:
It is important to emphasize the danger of embedding conditional structures in pseudo code: every IF...THEN must have a correspond ENDIF. Missing or superfluous ENDIF keywords often occur, but are easily spotted when pseudo code instructions are indented appropriately (i.e. pushed to the right inside structures, as in the second pseudo-code above).