
- Pascal Tutorial
- Pascal - Home
- Pascal - Overview
- Pascal - Environment Setup
- Pascal - Program Structure
- Pascal - Basic Syntax
- Pascal - Data Types
- Pascal - Variable Types
- Pascal - Constants
- Pascal - Operators
- Pascal - Decision Making
- Pascal - Loops
- Pascal - Functions
- Pascal - Procedures
- Pascal - Variable Scope
- Pascal - Strings
- Pascal - Booleans
- Pascal - Arrays
- Pascal - Pointers
- Pascal - Records
- Pascal - Variants
- Pascal - Sets
- Pascal - File Handling
- Pascal - Memory
- Pascal - Units
- Pascal - Date & Time
- Pascal - Objects
- Pascal - Classes
- Pascal Useful Resources
- Pascal - Quick Guide
- Pascal - Useful Resources
- Pascal - Discussion
Pascal - Nested if-then Statements
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.
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.
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 is true then check the following *) if ( b = 200 ) then (* if nested if condition is true then print 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 the following result −
Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200