The conditional structure allows you to decide what processing to do depending on whether a condition is true or not.
Let I1, I2, etc. be instructions and C1, C2, etc. be boolean expressions.
Syntax
if C1 then I1;
If condition C1 is true (the value of the boolean expression C1 is true), then instruction I1 is executed.
When multiple instructions are to be executed, the keywords begin and end are used to delimit these instructions.
Syntax
if C1 then
begin
I1;
I2;
end;
Syntax
if C1 then I1
else I2;
If condition C1 is true, then instruction I1 is executed, else instruction I2 is executed.
Syntax
if C1 then
begin
I1;
I3;
end
else
begin
I2;
I4;
end;
The else clause is never preceded by a semicolon ( ; ).
The else clause always refers to the nearest if clause.
The conditional structure can be nested in various ways.
Syntax
if C1 then
I1
else
if C2 then
I2
else
if C3 then
I3
else I;
Syntax
if C1 then
if C2 then
Ia
else
Ib
else
if C3 then
Ic
else
Id;
In a boolean expression we use comparison operators to compare values such as numbers.
Comparison operators
=
<>
<
<=
>
>=
Description
Equal to
Not equal to
Less than
Less than or equal
Greater than
Greater than or equal
Example
program example;
var
n : integer;
b : boolean;
begin
n := 12;
b := (n mod 2) = 0;
if b then
writeln(n, ' is even')
else
writeln(n, ' is odd');
end.
Example
program example;
var
n : integer;
begin
n := 12;
if (n mod 2) = 0 then
writeln(n, ' is even')
else
if (n mod 3) = 0 then
writeln(n, ' is odd and multiple of 3')
else
writeln(n, ' is odd and not multiple of 3');
end.
The multiple cases conditional structure allows you to decide what processing to do based on the value of an expression compared to a set of given constant values.
Let Ia, Ib, etc. be instructions.
Let E be an ordinal expression (its type is an integer, a character, a boolean, but neither a real nor a string).
Let V1, V2, etc. be ordinal constant values of the same type as E.
Syntax
case E of
V1 : Ia;
V2 : Ib;
V3, V4 : Ic; { list }
V5..V6 : Id; { range }
{...}
else I; { optional }
end;
In case the value of expression E is equal to V1 then the instruction Ia associated with V1 is executed, and so on.
And optionally, if none of these cases occurs, then the instruction I associated with the else clause is executed.
Example
program example;
var
c : char;
begin
c := 'a';
case c of
'a'..'z' : writeln('lowercase letter');
'A'..'Z' : writeln('uppercase letter');
'0'..'9' : writeln('digit');
else writeln('not alphanumeric');
end;
end.
Example
program example;
var
n : integer;
begin
n := 1;
case n of
1 : writeln('monday');
2 : writeln('tuesday');
3 : writeln('wednesday');
4 : writeln('thursday');
5 : writeln('friday');
6 : writeln('saturday');
7 : writeln('sunday');
else writeln('not a day');
end;
end.