[Next][Prev] [Right] [Left] [Up] [Index] [Root]

The if statement

The if-statement is a conditional statement. It causes execution of some statements to depend on the truth-value of a certain condition, given as a Boolean expression. If the condition is true, then the statements immediately after `then' are executed; if it is false then the statements after `else' are executed, provided that the `else' clause is present.

The syntax of the simple if-statement can be either of the following:

if CONDITION then
    STATEMENTS;
end if;

if CONDITION then
    STATEMENTS;
else
    STATEMENTS;
end if;

In the situation such that when the condition is false then another test is immediately made, the programming solution of nested if-statements can be avoided by `elif' clauses within a single if-statement. The syntax may be either of the following. Note that the `else' clause may be omitted, as for the case above:

if CONDITION then
    STATEMENTS;
elif CONDITION then
    STATEMENTS;
elif ...
else
    STATEMENTS;
end if;

if CONDITION then
    STATEMENTS;
elif CONDITION then
    STATEMENTS;
elif ...
end if;

Example

> n := Random(1, 100); 
> if not IsPrime(n) then
if> print n, Factorization(n);
if> end if;
90 [ <2, 1>, <3, 2>, <5, 1> ]

> mark := 76; // an examination grade, as a percentage
> if mark ge 85 then
if> print "High Distinction";
if> elif mark ge 75 then
if> print "Distinction";     
if> elif mark ge 65 then
if> print "Credit";     
if> elif mark ge 50 then
if> print "Pass";       
if> else
if> print "Fail";
if> end if;
Distinction

 [Next][Prev] [Right] [Left] [Up] [Index] [Root]