Pascal - Nested if-then Statements
- Details
- Category: Chapter 2
- Published: Sunday, 14 April 2013 14:27
- Written by Sternas Stefanos
- Hits: 25411
It is always legal in Pascal programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). Pascal allows nesting to any level, however, if depends on Pascal implementation on a particular system.
1. Syntax:
The syntax for a nested if statement is as follows:
if( boolean_expression 1)then if(boolean_expression 2)then S1 else S2;
You can nest else if-then-else in the similar way as you have nested if-then statement. Please note that, the nested if-then-else constructs gives rise to some ambiguity as to which else statement pairs with which if statement. The rule is that the else keyword matches the first if keyword (searching backwards) not already matched by an else keyword.
The above syntax is equivalent to
if( boolean_expression 1)then begin if(boolean_expression 2) then S1 else S2; end;
It is not equivalent to
if( boolean_expression 1)then begin if exp2 then S1 end; else S2;
Therefore if the situation demands the later construct, then you must put begin and end keywords at the right place.
2. Example:
program nested_ifelseChecking; var {local variable definition } a, b : integer; begin a :=100; b:=200; (* check the boolean condition *) if(a =100)then (*if condition istruethen check the following *) if( b =200)then (*if nested if condition istrue thenprint the following *) writeln('Value of a is 100 and value of b is 200'); writeln('Exact value of a is: ', a ); writeln('Exact value of b is: ', b ); end.
When the above code is compiled and executed, it produces following result:
Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200