Previous | Next | Table of Contents | Index | Program List | Copyright

4.1 Control Structures: Boolean Expressions and the IF Statement

In all the algorithms illustrated so far, each algorithm step is executed exactly once in the order in which it appears. Often we are faced with situations in which we must provide alternative steps that may or may not be executed, depending on the input data.

For example, in the simple payroll problem discussed in Chapter 2, a tax of $25 was deducted regardless of the employee's salary. It would be fairer to base the amount deducted on the employee's gross salary. For example, we might want the program to deduct a tax only if the employee's salary exceeds $100. Carrying this one step further, we might want the program to use tax brackets, that is, to deduct one tax percentage for salaries between $100 and $300 and a higher percentage for salaries greater than $300.

Boolean Expressions and Conditions

To achieve this goal, the computer must be able to answer questions such as, "Is gross salary greater than $100?" In Ada, this is accomplished by evaluating a Boolean expression. Assuming that the employee's salary is stored in the Float variable Gross, the Boolean expression corresponding to that question is

    Gross > 100.0
There are only two possible values for a Boolean expression: True or False. If Gross is greater than 100.00, the preceding Boolean expression evaluates to True; if Gross is not greater than 100.00, the expression evaluates to False. Chapter 7 examines the operators that can be used on Boolean expressions. For now, we will concentrate on learning how to write and use simple Boolean expressions called conditions.

Most conditions that we use will have one of the following forms:

     variable relational operator variable

     variable relational operator constant

Relational operators are the familiar symbols

All these operators should be familiar to you except the last. Ada uses the symbol pair /= to express the condition "not equal to." In mathematics, this is usually written [[opthyphen]], but this symbol does not appear on computer keyboards. Also, be careful that you write >= and not => for "greater than or equal to"--the latter symbol is used in Ada for other things, such as

 
    Ada.Text_IO.Put(Item => "Hello");

and its mistaken use as a relational operator will lead to a compilation error.

The variables in a Boolean condition can be of Integer, Float, or enumeration type. In the Integer and Float cases, the relational operators have their familiar meanings: 3 < 4, -17.5 > -30.4. In the case of enumeration types, the comparisons are with respect to the order in which the values are defined in the type definition. Given two types

    TYPE Days IS (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
    TYPE Colors  IS (Red, Orange, Yellow, Green, Blue, Purple);

these conditions are all true:

    Mon < Tue
    Wed /= Tue
    Wed = Wed
    Wed >= Tue
    
    Purple > Red
    Yellow < Green
    Green >= Yellow 

The conditions

    Purple > Fri
    3 <= 4.5
    Green > 2 

would cause compilation errors because the two values in each comparison are associated with different types and therefore cannot be compared--it would be like comparing apples and oranges.

If the integer variable I is 5, the Float variable X is 3.9, and the Days variable Today is Wed, these relations are true:

    I > 0
    X <= 3.9
    Today > Tue

Finally, we note that the Character type is defined as an enumeration type, and the relations are with respect to the alphabetic order. It's actually a bit more complicated than this; we'll come back to it in more detail in Chapter 7.

Example 4.1

The relational operators and some sample conditions are shown in Table 4.1. Each condition is evaluated assuming the variable values below.

 X   Power   MaxPow   Y   Item   MinItem   MomOrDad   Num   Sentinel
-5   1024    1024     7   1.5    -999.0    'M'        999   999

Table 4.1 Ada Relational Operators and Sample Conditions

Operator	Condition	Meaning				Value

<=		X <= 0		X less than or equal to 0	true
<		Power < MaxPow	Power less than MaxPow		false
>=		X >= Y		X greater than or equal to Y	false
>		Item > MinItem	Item greater than MinItem	true
=		MomOrDad = 'M'	MomOrDad equal to 'M'		true
/=		MinItem /= Item	MinItem not equal to Item	true
/=		Num /= Sentinel	Num not equal to Sentinel	false

The IF Statement

You can use the IF statement to select among several alternatives. An IF statement always contains a Boolean expression. For example, the IF statement

    IF Gross > 100.00 THEN
        Net := Gross - Tax;
    ELSE
        Net := Gross;
    END IF;

selects one of the two assignment statements listed. It selects the statement following THEN if the Boolean expression is true (i.e, if Gross is greater than 100.00); it selects the statement following ELSE if the Boolean expression is false (i.e., if Gross is not greater than 100.00).

Figure 4.1 is a graphic description, called a flow chart, of the preceding IF statement. Figure 4.1 shows that the condition enclosed in the diamond-shaped box (Gross > 100.00) is evaluated first. If the condition is true, the arrow labeled True is followed, and the assignment statement in the rectangle on the right is executed. If the condition is false, the arrow labeled False is followed, and the assignment in the rectangle on the left is executed.

Figure 4.1. Two-Alternative IF Statement

Figure 4.1

The preceding IF statement has two alternatives, but only one will be executed for a given value of Gross. Example 4.2 illustrates that an IF statement can also have a single alternative that is executed only when the condition is true.

Example 4.2

The following IF statement has one alternative, which is executed only when X is not equal to 0. It causes Product to be multiplied by X; the new value is then saved in Product, replacing the old value. If X is equal to 0, the multiplication is not performed. Figure 4.2 is a flow chart of this IF statement.

    -- Multiply Product by a nonzero X only
    IF X /= 0.0 THEN
        Product := Product * X;
    END IF;

Figure 4.2 Single-Alternative IF Statement

Figure 4.2

Example 4.3

The following IF statement has two alternatives. It displays either Hi Mom or Hi Dad depending on the character stored in the variable MomOrDad (type Character).

    IF MomOrDad = 'M' THEN
        Ada.Text_IO.Put(Item => "Hi Mom"); 
        Ada.Text_IO.New_Line;
    ELSE
        Ada.Text_IO.Put(Item => "Hi Dad");
        Ada.Text_IO.New_line;
    END IF;

Notice that the statement sequences may include one or more statements, all terminated by semicolons, and also that the END IF; is always required whether the IF statement has one alternative or two.

The forms of the IF statement used so far are summarized in the displays that follow.

SYNTAX DISPLAY
IF Statement (Two Alternatives)

Form:
IF condition THEN
    statement sequence T
ELSE 
    statement sequence F 
END IF;

Example:
IF X >= 0.0 THEN 
    Ada.Text_IO.Put(Item => "Positive");
ELSE 
    Ada.Text_IO.Put(Item => "Negative");
END IF;

Interpretation:
If the condition evaluates to true, then statement sequence T is executed and statement sequence F is skipped; otherwise, statement sequence T is skipped and statement sequence F is executed.

Note:
There is no semicolon after THEN or after ELSE. Inserting a semicolon here will cause a compilation error.

SYNTAX DISPLAY
IF Statement (One Alternative)

Form:
IF condition THEN
    statement sequence T 
END IF;

Example:
IF X > 0.0 THEN
    PosProd := PosProd * X;
    CountPos := CountPos + 1;
END IF;

Interpretation:
If the condition evaluates to true, then statement sequence T is executed; otherwise, it is skipped.

PROGRAM STYLE
Formatting the IF statement

In all the IF statement examples, the statement sequences are indented. If the word ELSE appears, it is entered on a separate line and aligned with the words IF and END IF. The format of the IF statment makes its meaning apparent. This is done solely to improve program readability and is highly recommended; the format used makes no difference to the compiler.

Exercises for Section 4.1

Self-Check

  1. Assuming X is 15.0 and Y is 25.0, what are the values of the following conditions?
    X /= Y     X < X    X >= (Y - X)    X = (Y + X - Y)
    
  2. What do the following statements display?
    a.
    IF 12 < 12 THEN
        Ada.Text_IO.Put(Item => "Never");
    ELSE
        Ada.Text_IO.Put(Item => "Always");
    END IF;
    

    b.
     
    Var1 := 15.0;
    Var2 := 25.12;
    IF (2*Var1) > Var2 THEN
        Ada.Text_IO.Put(Item => "OK");
    ELSE
        Ada.Text_IO.Put(Item => "Not OK");
    END IF;
    


Previous | Next | Table of Contents | Index | Program List | Copyright

Copyright © 1996 by Addison-Wesley Publishing Company, Inc.