Anda di halaman 1dari 17

Selecting Alternatives with if-then-else Statements

In the previous three lectures, we explained how a program can use a for loop to execute a certain
statement a fixed number of times. This is known as repetition. In this lecture, we will show how a
program can choose between alternative courses of action using selection statements. This results in a
statement being executed only if a certain condition is true. If the condition is false, another statement
is executed. Selection is achieved by using if-then-else statements.

7.1 Choosing Between Two Alternatives

In the programs we have seen so far, all the statements in the program are executed in the sequence
they are written. If the statements are part of a for loop, they are repeatedly executed until the
expression (the second part of the for loop) becomes false. However, it is often necessary to execute a
set of statements only if a certain condition is true. If the condition is false, another set of statements
should be executed.

For example, suppose we have to write a program which inputs a number (integer) from the user at the
keyboard and then determines if the number is even or odd. A number is even if there is no remainder
when it is divided by 2. A number is odd if the remainder is one when it is divided by 2. After reading the
number typed by the user, the program needs to find the remainder when the number is divided by 2. If
the number typed by the user is stored in a variable num, the remainder can be calculated using the
remainder operator, %:

remainder = num % 2;

A decision must now be made: is remainder equal to zero or is remainder equal to 1? This can be
expressed in a flow chart using a Decision symbol. As usual, there are two lines leaving the Decision
symbol, one to indicate what to do if the condition is true (Yes) and the other one to indicate what to do
if the condition is false (No). The Yes line leads to an output statement that displays that the number is
even; the No line leads to an output statement that displays that the number is odd. Only one of these
statements will be executed each time the program is run. However, regardless of the statement that is
chosen to be executed, after execution, the lines meet again. A flow chart to express the logic of the
program is given in Figure 7.1.

1
Figure 7.1: Flow Chart for Program Which Determines if a Number is Even or Odd

When a writing a for loop, the second section of the for loop contains an expression such as count <
10. A similar expression can be used to formulate the decision we now have to make, “is remainder

equal to zero”:

remainder == 0

2
This expression is used in an if-then-else statement to represent the “choosing between alternatives”
logic shown in Figure 7.1:

if (remainder == 0)
cout << num << " is an even number." << endl;
else
cout << num << " is an odd number." << endl;

Note that the expression or condition, remainder == 0, is enclosed between parentheses and comes
after the if keyword. Right after the condition is the statement to be executed if the condition
evaluates to true. This is followed by the else keyword, followed by the statement to be executed if the
condition evaluates to false.

Similar to when writing a for loop, an if-then-else statement can contain a compound statement
which is executed if the condition is true and another compound statement which is executed if the
condition is false. So, in general, an if-then-else statement can be written as follows:

if (condition) {
true-statement 1;
true-statement 2;

true-statement n;
}
else {
false-statement 1;
false-statement 2;

false-statement n;
}

Figure 7.2 contains the complete program for determining if a number input by the user is even or odd.
It also shows how the parts of the program are related to the flow chart given in Figure 7.1.

3
Figure 7.2: Relationship Between Program Containing if-then-else Statement and Flow Chart

7.2 Different Paths of Execution

Consider what happens when the program shown in Figure 7.2 is executed. Suppose the user enters 10
at the keyboard. The remainder when 10 is divided by 2 is zero, so the condition is true. This causes the
Yes line of the flow chart to be followed, resulting in the output being displayed that the number is even.
Note that the output statement which indicates that the number is odd is not executed at all. This is
shown in the flow chart of Figure 7.3 where the shaded symbols indicate the steps that are actually
executed when the user types 10 at the keyboard.

4
Figure 7.3: Flow Chart Showing Steps that are Actually Executed When num is 10

Suppose the user enters 11 at the keyboard. The remainder when 11 is divided by 2 is 1, so the
condition is false. This causes the No line of the flow chart to be followed, resulting in the output being
displayed that the number is odd. Now, the output statement which indicates that the number is even is
not executed at all. This is shown in the flow chart of Figure 7.4 where the shaded symbols indicate the
steps that are actually executed when the user types 11 at the keyboard.

5
Figure 7.4: Flow Chart Showing Steps that are Actually Executed When num is 11

From Figure 7.3 and Figure 7.4, it can be observed that the execution of an if-then-else statement
results in different execution paths through a program. Thus, it is possible for a program to do different
things each time it is run. This is one reason why computer programs are so powerful.

This section will conclude with another example. Suppose we have to write a program to calculate the
tax payable to the authorities when a parcel of land is purchased. If the land is residential land (type is
1), the rate of tax is 3% (or 0.03). Otherwise, the rate of tax is 7% (or 0.07). The flow chart for solving this

6
problem is given in Figure 7.5. As can be seen, taxRate is assigned the value of 0.03 if the type of land is
1. Otherwise, it is assigned the value of 0.07. Regardless of which path is chosen, the program goes on to
calculate and display the tax payable.

Figure 7.5: Flow Chart to Calculate Tax Payable on Purchase of a Parcel of Land

7
The corresponding program contains an if-then-else statement to assign the appropriate value to
taxRate, based on the type of land being purchased. The complete program is given below:

#include <iostream>

using namespace std;

int main ()
{
float landPrice;
int landType;
float taxRate;
float landTax;

cout << "Please enter land price: ";


cin >> landPrice;

cout << "Please enter land type: ";


cin >> landType;

if (landType == 1)
taxRate = 0.03;
else
taxRate = 0.07;

landTax = landPrice * taxRate;

cout << "Tax due on land purchase: " << landTax << endl;

return 0;

7.3 Choosing Between Three Alternatives

The if-then-else statement makes it possible for a program to choose between two alternatives.
However, what do we do if we have to choose from among three alternatives? For example, suppose
that there are three categories of tax when purchasing land, instead of two. If the land is residential
(type is 1), the rate of tax is 3%. If the land is commercial (type is 2), the rate of tax is 20%, and if the
land is agricultural (type is 3), the rate of tax is 7%. We can modify the flowchart in Figure 7.5 as follows.

After inputting the land price and the land type from the user, we check to determine if type is equal to
1. If so, taxRate is assigned the value 0.03. If not, we do another check to determine if type is equal to 2.
If so, taxRate is assigned the value 0.2. Otherwise, taxRate is assigned the value 0.07. The revised flow
chart will therefore contain two Decision boxes, as shown in Figure 7.6. Note that there is no need to
check if type is equal to 3; once it is established that type is not equal to 2 in the second Decision box,
this conclusion can be drawn immediately.

8
Start

input
price, type

Yes is No
type = 1?

taxRate = is No
0.03 type = 2?

Yes

taxRate = taxRate =
0.2 0.07

tax =
price x
taxRate

output
taxRate, tax

End

Figure 7.6: Revised Flow Chart to Determine Tax Payable on Purchase of Land

9
The corresponding program will also contain two if-then-else statements. The second if-then-else
statement is written completely inside the else part of the first if-then-else statement, since it must
only be executed if the condition of the first if-then-else statement is false. The code is given below:

#include <iostream>

using namespace std;

int main ()
{
float landPrice;
int landType;
float taxRate;
float landTax;

cout << "Please enter land price: ";


cin >> landPrice;

cout << "Please enter land type: ";


cin >> landType;

if (landType == 1)
taxRate = 0.03;
else {
if (landType == 2)
taxRate = 0.2;
else
taxRate = 0.07;
}

landTax = landPrice * taxRate;

cout << "Tax due on land purchase: " << landTax << endl;

return 0;

The inner if-then-else statement is said to be nested within the outer if-then-else statement. By
nesting if-then-else statements within other if-then-else statements, it is possible to write
selection statements that can choose from 3 or more alternative courses of action. Note that the
statement which is executed if the condition of the inner if-then-else statement (landType == 2) is
true (or false) may be a compound statement.

7.4 Selecting Alternatives Within a for Loop

We have previously shown how a for loop can be used to display the numbers 0 to 9, each one in a new
line. The for loop executes 10 times; each time through the loop, the value of the loop control variable,
count, is displayed using the statement:

10
cout << count;

We would like to write a program which, instead of displaying the value of count, inputs 10 numbers
from the user via the keyboard. As each number is read from the keyboard, the program should
determine if it is even or odd.

Now, the program in Section 7.1 reads a number from the keyboard and uses an if-then-else
statement to determine if the number is even or odd. Most of the code from this program can therefore
be used in our new program. All we have to do is replace the code which displays the value of count with
the code from the program in Section 7.1. This is shown using flow charts in Figure 7.7. The resulting
flow chart is shown in Figure 7.8.

Figure 7.7: Replacing Output Statement with an if-then-else Statement

11
Figure 7.8: Flow Chart for Determining if 10 Numbers are Even or Odd

12
The complete program is given below. As can be seen, the if-then-else statement is completely
nested within the for loop.

#include <iostream>

using namespace std;

int main ()
{
int count;
int num;
int remainder;

for (count = 0; count < 10; count = count + 1) {

cout << "Please enter an integer: ";


cin >> num;

remainder = num % 2;

if (remainder == 0)
cout << num << " is an even number." << endl;
else
cout << num << " is an odd number." << endl;
}

return 0;

Figure 7.9 shows how the statements in the program are related to the steps in the flow chart given in
Figure 7.8.

13
#include <iostream>

using namespace std;

int main ()
{
int count;
int num;
int remainder;

for (count = 0; count < 10; count = count + 1) {

cout << "Please enter an integer: ";


cin >> num;

remainder = num % 2;

if (remainder == 0)
cout << num << " is an even number." << endl;
else
cout << num << " is an odd number." << endl;
}

return 0;

Figure 7.9: Relationship Between Program with Nested if-then-else Statement and Flow Chart

Before concluding this lecture, it is instructive to consider another program which requires us to
determine the winner in an election. There are two candidates, Candidate 1 and Candidate 2, and 20
voters. The vote for each voter is entered by the user at the keyboard. If the vote is 1, it is a vote for
Candidate 1; if the vote is 2, it is a vote for Candidate 2.

A for loop can be used to read the 20 votes from the user at the keyboard. Each time a vote is read, it is
determined whether it is 1 or 2, using a Decision box. If it is 1, 1 is added to the number of votes
obtained by Candidate 1; if it is 2, 1 is added to the number of votes obtained by Candidate 2. The

14
number of votes obtained by each candidate is initially set to zero. After the for loop exits, there is no
more data to input from the user. However, the winner must be determined by comparing the votes of
each candidate. Thus, the No arrow which goes from the for loop Decision box when the loop exits, now
leads to another if-then-else Decision box to determine who won the election. Figure 7.9 is the flow
chart which solves the problem.

The code for the program is listed below. As can be seen, there are two if-then-else statements. One
is nested within the for loop, to count the number of votes obtained by the respective candidates as
the votes are being read from the keyboard. The other one is executed after the for loop has exited; it
is used to determine which of the candidates (if any) won the election, after the votes have been
counted.

#include <iostream>

using namespace std;

int main ()
{
int count;
int vote;
int candidate1, candidate2;

candidate1 = 0;
candidate2 = 0;

for (count = 0; count < 20; count = count + 1) {

cout << "Please enter vote (1 for Candidate 1, 2 for Candidate 2): ";
cin >> vote;

if (vote == 1)
candidate1 = candidate1 + 1;
else
candidate2 = candidate2 + 1;
}

if (candidate1 == candidate2)
cout << "Candidates have tied with " << candidate1 << " votes." << endl;
else {
if (candidate1 > candidate2)
cout << "Candidate 1 has won with " << candidate1 << " votes." << endl;
else
cout << "Candidate 2 has won with " << candidate2 << " votes." << endl;
}

return 0;

15
Figure 7.9: Flow Chart for Election Problem

16
7.5 Exercises

1. Consider the equation ax2 + bx + c = 0. This equation has “real” roots if b2 - 4*a*c is greater than or
equal to zero. Otherwise, the equation is said to have “imaginary” roots. Write a program that
inputs a, b, and c for a given equation and determines if the equation has real or imaginary roots.
You do not have to find the actual roots.

2. In Section 7.4, a program is given which determines if a set of numbers entered by the user at the
keyboard is even or odd. Revise the program so that it will count the number of even and odd
numbers instead of displaying a message on the monitor. At the end of the program, give the
percentage of even and odd numbers that were entered by the user.

3. In a certain country, the tax payable on a person’s income is calculated as follows: If the person’s
annual income is less than or equal of $72,000.00, he/she pays 5% of his/her income as tax.
Otherwise, the person pays 5% of $72,000.00 as tax plus 25% on the amount greater than
$72,000.00.

4. If an angle of a triangle is equal to 90o, it is said to be a right angle; if it is less than 90o, it is said to be
acute and if it is greater than 90o, it is said to be obtuse. Write a program which inputs the value of
an angle of a triangle from the keyboard and determines what kind of angle it is.

5. Selection statements are often used to perform data validation in a program, i.e., to ensure that the
data if acceptable before it is processed further. Write a program which inputs a number, n, from
the user and finds the square root of the number (√n) as well as the reciprocal of the number (1/n).
If n is negative, the program should display an error message instead of calculating the square root.
If n is zero, the program should display an error message instead of calculating the reciprocal (since
we cannot divide by zero).

The following program shows how to calculate the square root of a number. Note that the program
has an additional line at the top, #include <cmath>. The sqrt function is called to calculate the
square root of 49.0. The value is stored in the sqrRoot variable which is then displayed. The sqrt
function can be called with variables instead of fixed numbers, e.g., sqrt (num).

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
float sqrRoot;

sqrRoot = sqrt (49.0);

cout << "The square root of 49.0 is: " << sqrRoot;

return 0;

17

Anda mungkin juga menyukai