using compound relational tests or using nested conditions. When conditions are nested the if-else/ifelse-
if construct may contain other if-else/if-else-if constructs within themselves. In nesting you must be careful to keep track of different ifs and corresponding elses. Consider the following example:
if (a>=2)
if (b >= 4)
printf("Result 1");
else
printf("Result 2");
An else matches with the last if in the same block. In this example the else corrosponds to the second if. Therefore if both a >= 2 AND b >= 4 are TRUE “Result 1” will be displayed; if a>= 2 is TRUE but if b >= 4 is FALSE “Result 2” will be displayed. If a >= 2 is FALSE nothing will be displayed. To reduce any confusion braces can be used to simplify the source code. Therefore the above can be rewritten as follows:
if (a>=2)
{
if (b >= 4)
printf("Result 1");
else
printf("Result 2");
}
In the above, if else is to be associated with the first if then we can write as follows:
if (a>=2)
{
if (b >= 4)
printf("Result 1");
}
else
printf("Result 2");
Exercise 4.4 – Rewrite the program in Example 4.3 using nested conditions (i.e. using braces ‘{‘ and
‘}’.
No comments:
Post a Comment