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

4.5 Control Structures: The Multiple-Alternative IF Statement

Until now, we have used IF statements to implement decisions involving one or two alternatives. In this section, you will see how the IF statement can be used to implement decisions involving more than two alternatives.

Example 4.5

The IF statement below has three alternatives. It causes one of three variables (NumPos, NumNeg, or NumZero) to be increased by 1 depending on whether X is greater than 0, less than 0, or equal to 0, respectively. This statement might be part of a program to keep track of the number of positive, negative, and zero values in a set of values. It assumes that all the variables have been properly initialized.

    -- Increment NumPos, NumNeg, or NumZero depending on X
    IF X > 0 THEN
        NumPos := NumPos + 1; 
    ELSIF X < 0 THEN
        NumNeg := NumNeg + 1;
    ELSE -- X = 0
        NumZero := NumZero + 1;
    END IF;

The execution of this IF statement proceeds as follows: The first condition (X > 0) is tested; if it is true, the statement NumPos := NumPos+1 increments NumPos by 1 and the rest of the IF statement is skipped. If the first condition is false, the second condition (X < 0) is tested; if it is true, NumNeg is incremented; otherwise, NumZero is incremented. It is important to realize that the second condition is tested only when the first condition is false. Figure 4.6 diagrams the execution of this statement. Each condition is shown in a diamond-shaped box. If a condition is true, its arrow labeled True is followed. If a condition is false, its arrow labeled False is followed. This diagram shows that one and only one of the statement sequences in a rectangular box will be executed. A trace of the IF statement for X = -7 is shown in Table 4.4.

Figure 4.6
Flow Chart of the IF Statement in Example 4.5

Figure 4.6

Table 4.4 Trace of IF Statement in Example 4.5 for X = -7

Statement Part	X	Effect
	-7
IF X > 0 THEN		-7 > 0 is false
ELSIF X < 0 THEN		-7 < 0 is true
  NumNeg := NumNeg + 1;	 	Add 1 to NumNeg

SYNTAX DISPLAY
Multiple Alternative IF Statement

Form:
IF condition1 THEN
    statement sequence1
ELSIF condition2 THEN
    statement sequence2
    ...
ELSIF conditionk THEN
    statement sequencek
ELSE
    statement sequencen
END IF;

Example:
IF N >= 0 THEN
    Ada.Text_IO.Put(Item=>"Positive");
ELSIF N = 0 THEN
    Ada.Text_IO.Put(Item=>"Zero");
ELSE 
    Ada.Text_IO.Put(Item=>"Negative");
END IF;

Interpretation:
The conditions in a multiple alternative IF statement are evaluated from top to bottom until a true value is obtained. The statement sequence following the first true condition is executed and the rest of the IF statement is skipped. If every condition is false, statement sequencen (between ELSE and END) is executed.

Notes:
At most one statement sequence is executed. If ELSE and statement sequencen are present, exactly one statement sequence is always executed. If ELSE and statement sequencen are omitted, no statement sequence is executed when every expression is false.

Also note the spelling required by Ada: ELSIF is spelled without a second E or space; END IF must have a space between END and IF.

PROGRAM STYLE
Writing a Multiple-Alternative IF Statement

When writing a multiple alternative IF statement, align the reserved words IF, ELSE, ELSIF, and END IF and indent each statement sequence consistently. This is done to make the IF statement more readable; indentation is ignored by the compiler.

Order of Conditions

Very often the conditions in a multiple-alternative decision are not mutually exclusive. This means that it may be possible for more than one condition to be true for a given data value. If this is the case, the order of the conditions becomes very important because only the statement sequence following the first true condition is executed.

Example 4.6

The table below describes the assignment of grades based on an exam score.

Exam Score 	Grade Assigned 

90 and above 	A
80-89		B 
70-79		C
60-69		D
below 60 	F

The multiple alternative IF statement below displays the letter grade assigned according to this table. The last three conditions are true for an exam score of 85; however, a grade of B is assigned because the first true condition is Score >= 80.

    -- correct grade assignment
    IF Score >= 90 THEN
        Ada.Text_IO.Put (Item=>'A');
    ELSIF Score >= 80 THEN
        Ada.Text_IO.Put (Item=>B');
    ELSIF Score >= 70 THEN
        Ada.Text_IO.Put (Item=>'C');
    ELSIF Score >= 60 THEN
        Ada.Text_IO.Put (Item=>'D');
    ELSE
        Ada.Text_IO.Put (Item=>'F');
    END IF;

It would be wrong to write the decision as shown next. All passing exam scores (60 or above) would be incorrectly categorized as a grade of D because the first condition would be true and the rest would be skipped. Writing the IF this way would be a mistranslation of the table into code.

    -- incorrect grade assignment 
    IF Score >= 60 THEN
        Ada.Text_IO.Put (Item=>'D');
    ELSIF Score >= 70 THEN
        Ada.Text_IO.Put (Item=>'C');
    ELSIF Score >= 80 THEN
        Ada.Text_IO.Put (Item=>'B');
    ELSIF Score >= 90 THEN
        Ada.Text_IO.Put (Item=>'A');
    ELSE
        Ada.Text_IO.Put (Item=>'F');
    END IF;

Example 4.7

You can use a multiple alternative IF statement to implement a decision table that describes several alternatives. Let's say you are an accountant setting up a payroll system for a small firm. Each line of Table 4.5 indicates an employee's salary range and a corresponding base tax amount and tax percentage. Given a salary amount, the tax is calculated by adding the base taxfor that salary range and the product of the percentage of excessand the amount of salary over the minimum salary for that range.

Table 4.5
Tax Table for Example 4.7

	Salary Range		Base Tax	Percentage of Excess 

1	0.00-1499.99		0.00		15% 
2	1500.00-2999.99		225.00		16% 
3	3000.00-4999.99		465.00		18% 
4	5000.00-7999.99		825.00		20%
5	8000.00-14999.99	1425.00		25% 
For example, the second line of the table specifies that the tax due on a salary of $2000.00 is $225.00 plus 16% of the excess salary over $1500.00 (i.e., 16% of $500.00). Therefore, the total tax due is $225.00 plus $80.00, or $305.00.

The IF statement in Figure 4.7 implements the tax table. If the value of Salary is within the table range (0.00 to 14999.99), exactly one of the statements assigning a value to TAX will be executed. A trace of the IF statement for Salary = $2000.00 is shown in Table 4.6. The value assigned to Tax is $305.00, as desired.

Figure 4.7
IF statement for Table 4.5

IF Salary < 0.0 THEN
    Ada.Text_IO.Put (Item=>"Error! Negative salary $");
    Ada.Float.Text_IO.Put (Item=>Salary, Fore=>1, Aft=>2,
Exp=0);
    Ada.Text_IO.New_Line;
ELSIF Salary < 1500.00 THEN -- first range
    Tax := 0.15 * Salary;
ELSIF Salary < 3000.00 THEN -- second range
    Tax := (Salary - 1500.00) * 0.16 + 225.00;
ELSIF Salary < 5000.00 THEN -- third range
    Tax := (Salary - 3000.00) * 0.18 + 465.00;
ELSIF Salary < 8000.00 THEN -- fourth range
    Tax := (Salary - 5000.00) * 0.20 + 825.00;
ELSIF Salary < 15000.00 THEN -- fifth range
    Tax := (Salary - 8000.00) * 0.25 + 1425.00;
ELSE
    Ada.Text_IO.Put (Item=>"Error! Too large salary $");
    Ada.Float.Text_IO.Put (Item=>Salary, Fore=>1, Aft=>2, Exp=0);
     Ada.Text_IO.New_Line;
END IF;

Table 4.6
Trace of IF Statement in Fig. 4.7 for Salary = $2000.00

Statement Part		Salary		Tax	Effect

			2000.00		?
IF Salary < 0.0					2000.0 < 0.0 is false
ELSIF Salary < 1500.00				2000.0 < 1500.0 is false
ELSIF Salary < 3000.00				2000.0 < 3000.0 is true
  Tax := (Salary - 1500.00)				difference is 500.00
         * 0.16						product is 80.00
         + 225.00			305.00		sum is 305.00 

PROGRAM STYLE
Validating the Value of Variables

It is important to validate the value of a variable before you perform computations using invalid or meaningless data. Instead of computing an incorrect tax amount, the IF statement in Fig. 4.7 displays an error message if the value of Salary is outside the range covered by the table (0.0 to 14999.99). The first condition is used to detect negative salaries, and an error message is displayed if Salary is less than zero. All conditions evaluate to False if Salary is greater than 14999.99, and the alternative following ELSE displays an error message.

Nested IF Statements

The statement sequence inside a control statement can contain another control statement. For example, an IF statement can contain another IF. The second control statement is said to be nested inside the first control statement. The inner control statement can itself contain a control statement; in fact, there is no theoretical limit on the depth to which control statements can be nested.

The ability to nest control statements allows us to write very sophisticated programs. In Chapters 5 and 6 we will introduce many examples of IF statements nested inside loops and vice versa. For the time being, consider the following example.

Example 4.8

Depending on a student's Grade Point Average (GPA), the following fragment displays one of three messages. If the GPA is less than or equal to 1.5, the painful message following the second ELSE is displayed. If GPA is greater than 1.5, the inner IF statement is executed, and a more pleasant message is displayed.

    IF GPA > 1.5 THEN
        IF GPA < 3.0 THEN
            Ada.TextIO.Put(Item => "Progressing satisfactorily");
        ELSE
        	Ada.Text_IO.Put (Item => "Made the Dean's List - send money");
        END IF;
    ELSE 
        Ada.Text_IO.Put (Item => "Flunked out");
    END IF;

The nested statements below have the same effect as the ones above. Again, the inner IF statement is executed when GPA exceeds 1.5.

    IF GPA <= 1.5 THEN
        Ada.Text_IO.Put (Item => "Flunked out");
    ELSE
        IF GPA < 3.0 THEN
        	Ada.Text_IO.Put (Item => "Progressing satisfactorily");
        ELSE 
        	Ada.Text_IO.Put (Item => "Made the Dean's List - send money");
        END IF;
    END IF; 

Nested IF statements can sometimes be confusing to write and to read. Often, a single multiple-alternative IF statement can replace nested IF statements, resulting in a more readable program. Verify for yourself that the IF statement below has the same effect as the earlier nested IF statements.

    IF GPA <= 1.5 THEN
        Ada.Text_IO.Put (Item => "Flunked out");
    ELSIF GPA < 3.0 THEN
        Ada.Text_IO.Put (Item => "Progressing satisfactorily");
    ELSE
        Ada.Text_IO.Put (Item => "Made the Dean's List - send money");
    END IF;

PROGRAM STYLE
Indentation Conventions for Nested Control Structures

It is a good idea to develop a consistent indentation style for nested control structures. Note in the examples above that the entire nested IF is indented the same amount as the Put following the ELSE.

Developing a consistent indentation style is one way of making your programs clear and easy to read. Many companies have adopted companywide or projectwide programming style standards that include indentation rules. This makes it easy for programmers to read each other's source code. There is no one "best" indentation rule; the most important principle is consistency.

In this book, we indent each structure several spaces deeper than the structure within which it is nested. The complete program examples use a consistent indentation of two spaces, and the code fragments in the text are usually indented a bit more for added clarity. We recommend an indentation convention similar to that used in the programs. If your teacher states different rules, follow them consistently.

Exercises for Section 4.5

Self-Check

  1. Trace the execution of the IF statement in Fig. 4.7 for Salary = 13500.00.
  2. What would be the effect of reversing the order of the first two conditions in the IF statement of Fig. 4.7?

Programming

  1. Rewrite the IF statement for Example 4.8 using only the relational operator < in all conditions.
  2. Implement the decision table below using a multiple-alternative IF statement. Assume that the grade point average is within the range 0.0 through 4.0.
      Grade Point Average        Transcript Message
    
         0.0-0.99             Failed semester -- registration suspended
         1.0-1.99             On probation for next semester
         2.0-2.99             (no message)
         3.0-3.49             Deans list for semester
         3.5-4.0              Highest honors for semester
    


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

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