next up previous contents
Next: Examples of Problem Solving Up: Nested Statements Previous: Nested Statements   Contents

Conditional Statements

For beginners, nested conditional statements are particularly tricky. For example, consider the following example:

if x < 0 then
  writeln('x is negative')
else
  writeln('x is non-negative')

It is important not to use a semi-colon after writeln('x is negative')! This is because the reserved word else does not begin another statement. The reserved word is already acting as a separator between the statment to execute when the condition is true and the statement to execute when the condition is false. If you put a semicolon after writeln('x is negative'), you end up with the following program:

if x < 0 then
  writeln('x is negative');
else
  writeln('x is non-negative')

The compiler chokes. Although it is okay up to the semicolon, it also thinks the semicolon is separating the conditional statement itself from the next statement. Unfortunately, else is still is part of the conditional statement. No statement can begin with the reserved word else, and this is why the compiler chokes.

Another common issue with conditional statements is how else is matched with if reserve words. Consider the following poorly formatted program.

if x < a then
if x > b then
writeln('hahaha')
else
writeln('hehehe')
else if x < c then
writeln('hohoho')
else
writeln('hihihi')

This program fragment contains the same number of ifs, thens and elses. This code even compiles! However, can you tell what conditions lead to the printing of ``hahaha'', ``hehehe'', ``hohoho'' and ``hihihi''?

The reserved word if is like an open paranthesis. The reserved word then is like a close paranthesis. This means it is going to close the most recent unclosed if. The same applies to else, it close the most recent unclosed then.

If I am to use indentation to indicate how the code is nested, the previous code should be reformatted as follows:

if x < a then
  if x > b then
    writeln('hahaha')
  else
    writeln('hehehe')
else 
  if x < c then
    writeln('hohoho')
  else
    writeln('hihihi')

Ah, much better! Now we understand the program behaves as follows:

If you prefer a more visual representation, figure 6.1 illustrates the same logic.

Figure 6.1: The flowchart of a nested structure of conditional statements.
\includegraphics{nestedcond}


next up previous contents
Next: Examples of Problem Solving Up: Nested Statements Previous: Nested Statements   Contents
Tak Auyeung 2003-12-03