Docsity

Selection Statements: Using if-then-else in Programming, Lecture notes of Computer Programming

Toggle sidebar
bg1
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.
Figure 7.1: Flow Chart for Program Which Determines if a Number is Even or Odd
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Selection Statements: Using if-then-else in Programming and more Lecture notes Computer Programming in PDF only on Docsity!

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.

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 <

  1. A similar expression can be used to formulate the decision we now have to make, “is remainder equal to zero”:

remainder == 0

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.

  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

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 using namespace std; int main () { float landPrice; int landType; fl float taxRate;oat 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.

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

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 using namespace std; int main () { float landPrice; int landType; fl float taxRate;oat 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 complete program is given below. As can be seen, the if-then-else statement is completely nested within the for^ loop.

#include 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; cout << num << " is an even number." << endl;if (remainder == 0) elsecout << 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.

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 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 using namespace std; int main (){ int vote;int count; 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; }

}