"If" Statements
Peter Suber, Computer Science, Earlham College

We often want an action to take place if a certain condition is met, and not otherwise.

(1)if BowlEmpty then writeln('Feed the cat!');

(2)if (Diameter > MyHead) then writeln('Yes, I''ll crawl in.');

In Pascal, the syntax for these statements is as simple as it is in English. The reserved word if is followed by the condition on which the action depends. The reserved word then is followed by the action that depended on the condition. Finally, a semi-colon follows the action statement.

(3)if {condition} then {action};

The condition can be any expression that evaluates to true or false. Remember that boolean variables are like numerical variables, except that they represent truth-values (of which there are only two, true and false) rather than numerical values. So the condition of an "if" statement can be a boolean variable.

Equality and inequality relations between numbers also evaluate to true or false; so they can also stand in the "if-clause". For example, "IQ < ShoeSize" and "IQ = ShoeSize" are either true or false, while "IQ + ShoeSize" is some number. The requirement that the "if-clause" be some truth or falsehood (as opposed to some number or character or string) reflects the way we use if in English:

(4)if {some statement is true} then {do something};

Review of Boolean variables

In example (1) above, "BowlEmpty" is a boolean variable. That means that instead of taking a number or character as a value, it takes true or false as its value. True and false are reserved words in Pascal. They function in Pascal exactly like the numerals 1, 2, 3, ..., namely, as values that can be assigned to variables (of the right type). Booleans are declared to be of type boolean:

var BowlEmpty : boolean;

They take assignments to boolean values:

BowlEmpty := true;

Note that "if BowlEmpty" is exactly equivalent to "if (BowlEmpty = true)". We can add the "= true" for emphasis, or as a reminder to ourselves if we forget how Boolean variables behave, but it is not necessary. I rarely use this construction in practice, but I do so in this handout to underline the way in which "if-clauses" and Boolean variables behave.

We can ask whether a Boolean variable is false in two ways as well: "if (BowlEmpty = false)" and "if not BowlEmpty".

If the "if-clause" is true, or if its condition is met, then the "then-clause" or action statement is executed. If the condition is not met, the "then-clause" is skipped and processing resumes with the next statement after the if statement.

(5)if (WeAreSmart = true) then (WarIsPossible := false);
writeln('Prepare for war.');
{the "writeln" is executed no matter what happens in the "if" statement.}

Sometimes we want an action to depend on more than one condition. We join our conditions with and.

(6)if PoolFull and SwimsuitOn
then writlen('Yes, I''ll dive in.');

(7)if (HadMeans = true)
and (HadMotive = true)
and (HadOpportunity = true)
and (BribeSufficient = false)
then writeln('We have reached a verdict, Your Honor.');

Sometimes an action depends on just one condition, but it could be any one of several conditions. Join the conditions with or.

(8)if (VisibleMold = false)
or (MikeyAteSomeFirst = true)
then writeln('Yes, I''ll have a bite.');

(9)if (Title = 'Miss')
or (Title = 'Mrs.')
then Title := 'Ms.';

We can mix and and or statements.

(10)if (PoolFull
and SwimsuitOn)
or BribeSufficient
then writlen(Yes, I''ll dive in.');

Notice how the parentheses in (10) make clear that we are saying

(x and y) or z

rather than

x and (y or z)

which are not equivalent.

Sometimes we want one action to occur if the condition is met, and another action to take place if the condition is not met. In English we'd say something like, "if you have insurance, then don't worry; otherwise, you're in really deep trouble." In Pascal, it's virtually the same. We introduce the reserved word else.

(11)if (HasInsurance = true)
then writeln('No problemo!')
else writeln('Ooops.');

(12)if (Heads = true)
then writeln('I won fair and square!')
else writeln('I had my eye lashes crossed!');

(13){Program asks user: 'Is Sandy a woman or a man?'}
if (Answer = 'woman')
then writeln('Dear Ms. Beach,')
else writeln('Dear Mr. Beach,');

Notice that there is no semi-colon after the "then-clause" and before the "else-clause". When we use "else-clauses", then the if statement doesn't end until the end of the "else-clause".

The "then" and "else" clauses can contain any kind of action statement. Sometimes we want more than one action to ensue if a condition is met. Then we should use a compound statement.

(14)if (Naughty = true) then begin
writeln('If I ever catch you doing that again, I''ll...');
writeln('And I''ll write to your parents.');
end; {then}

(15)if (CashOffered > Cost) then begin
end {then} else begin {if not enough money offered}
writeln('What you cheapskate?');
writeln('Please to give $',Cost-CashOffered:1:2,' more.');
end; {else}

Notice that the sub-statements inside the compound statements are followed by semi-colons. But the compound statement in the "then-clause" has no semi-colon after its end and before else.

Digression on compound statements

We haven't had compound statements yet, but they should cause no trouble. In English we can combine two or more simple sentences into a compound sentence in many ways. Here's one: "The moon is made of green cheese and I have astronomy in 10 minutes and I am hungry." In Pascal we can treat a bunch of statements as just one large or compound statement by sticking them in between a begin and an end. It's as if begin and end were parentheses or brackets marking off the group of statements for treatment as a single unit. Begin and end serve the same function in the mainline of a program and inside procedures.

Clear enough, you say, but why bother? The answer is that the "then" and "else-clauses" of an if statement expect just one statement each. So if we want many things to happen we have to state them in a single compound statement: begin...{many action statements}...end.

There is nothing wrong with putting just one action statement between begin and end --or even no actions at all. Hence, many Pascal programmers make it a rule to use compound statements in every "then-" and "else-clause", even if they have only one action in mind at the time they are writing. That way, they can go back later and add more statements without fuss.

We said that the "then-" and "else-clauses" can contain any kind of action statement. That means they can contain other if statements. These can get complex, but the following examples should give you the idea.

(16)if (BearsLiveYoung = true)
then if (HasBeak = true)
then writeln('It''s a platypus.')
else if (TwoStoryNeck = true)
then writeln('It''s a giraffe.')
else writeln('Give me a clue.')
else writeln('Not a mammal.');

(17)if (HasExperience = true)
then if (FreshOutOfCollege = true)
then writeln('Why weren''t you studying?')
else writeln('Sorry, we can''t afford you.')
else writeln('Sorry, our position has been filled.');

Nested if-then-else statements can become confusing. Remember this rule: an "else-clause" belongs to the most recent prior "then-clause" not already paired up with an "else-clause". Also remember this advice: use visual structure (white space) to reflect logical structure.

If you write an interactive program that asks the user a yes-or-no question, then it's easy to use an if statement to analyze the user's answer.

(18)write('Should I do the thing we discussed? Y/N: ');
if (Answer = 'y') or (Answer = 'Y')
then writeln('Erasing all your files...')
else writlen('Good career move.');

But how would you use if statements to analyze the user's answer if there were three or more possible replies?

(19)writeln('I''m gathering data for an experiment in Psych 11.');
writeln('Please cooperate. I need the credit.');
writeln('Are you a First-born child, Later-born child, or an Only child?');
writeln('Enter F, L, or O.');
if Answer = {...finish this if statement yourself...}

This file is an electronic hand-out for the course, Programming and Problem Solving.

Ribbon] Peter Suber, Department of Philosophy, Earlham College, Richmond, Indiana, 47374, U.S.A.
peters@earlham.edu. Copyright © 1997, Peter Suber.