You are here: Home » Content » Selection Statements
Quality
Affiliated with  (?)
This content is either by members of the organizations listed or about topics related to the organizations listed. Click each link to see a list of all content affiliated with the organization.
Lenses
Tags  (?)
These tags come from the endorsement, affiliation, and other lenses that include this content.

Selection Statements

Module by: Dr. Duong Tuan Anh

Summary: The flow of control refers to the order in which a program’s statements are executed. Unless directed otherwise, the normal flow of control for all programs is sequential. This means that statements are executed in sequence, one after another, in the order in which they are placed within the program. Selection, repetition and function invocation structures permit the flow of control to be altered in defined ways. This chapter introduces to you C++’s selection statements. Repetition and invocation techniques are presented in the next two chapters.

Selection Criteria

Relational Operators

Relational operators are used to compare two operands for equality and to determine if one numeric value is greater than another. A Boolean value of true or false is returned after two operands are compared. The list of relational operators is given below.
Figure 1: Relational operators
Example:
a = = b
(a*b) != c
s == ‘y’
x<= 4
The value of a relational expression such as a > 40 depends on the value stored in the variable a.

Logical Operators

Logical operators, AND, OR and NOT are used for creating more complex conditions. Like relational operators, a Boolean value of true or false is returned after the logical operation is executed.
When the AND operator, &&, is used with two simple expressions, the condition is true only if both individual expressions are true by themselves.
The logical OR operator, ||, is also applied with two expressions. When using the OR operator, the condition is satisfied if either one or both of the two expressions are true.
The NOT operator,!, is used to change an expression to its opposite state; thus, if the expression has any nonzero value (true),! expression produces a zero value (false). If an expression is false,! expression is true (and evaluates to false).
Example:
(age > 40) && (term < 10)
(age > 40) || (term < 10)
!(age > 40)
( i==j) || (a < b) || complete
The relational and logical operators have a hierarchy of execution similar to the arithmetic operators. The following table lists the precedence of these operators in relation to the other operators we have used.
Figure 2: Associativity of operators
Example: Assume the following declarations:
char key = ‘m’;
int i = 5, j = 7, k = 12;
double x = 22.5;
Figure 3: Results of expressions
By evaluating the expressions within parentheses first, the following compound condition is evaluated as:
Figure 4: Evaluation process

The bool Data Type

As specified by the ANSO/ISO standard, C++ has a built-in Boolean data type, bool, containing the two values true and false. As currently implemented, the actual values represented by the bool values, true and false, are the integer values 1 and 0, respectively. For example, consider the following program, which declares two Boolean variables:
Example
#include<iostream.h>
int main()
{
bool t1, t2;
t1 = true;
t2 = false;
cout << “The value of t1 is “<< t1
<< “\n and the value of t2 is “<< t2 << endl;
return 0;
}
The output of the program is:
The value of t1 is 1
and the value of t2 is 0

The If-Else Statement

The if-else statement directs the computer to select a sequence of one or more statements based on the result of a comparison.
The syntax for an if .. else statement:
if (conditional expression) {
statements;
}
else {
statements;
}
Figure 5: Flowchart of statement

Example 1

We construct a C++ program for determining income taxes. Assume that these taxes are assessed at 2% of taxable incomes less than or equal to $20,000. For taxable income greater than $20,000, taxes are 2.5% of the income that exceeds $20,000 plus a fixed amount of $400. (The flowchart of the program is given in Figure 2.)
#include <iostream.h>
#include <iomanip.h>
const float LOWRATE = 0.02; // lower tax rate
const float HIGHRATE = 0.025; // higher tax rate
const float CUTOFF = 20000.0; // cut off for low rate
const float FIXEDAMT = 400; // fixed dollar amount for higher rate amounts
int main()
{
float taxable, taxes;
cout << "Please type in the taxable income: ";
cin >> taxable;
if (taxable <= CUTOFF)
taxes = LOWRATE * taxable;
else
taxes = HIGHRATE * (taxable - CUTOFF) + FIXEDAMT;
// set output format
cout << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint)
<< setprecision(2);
cout << "Taxes are $ " << taxes << endl;
return 0;
}
Figure 6: Flowchart of example
The results of the above program:
Please type in the taxable income: 10000
Taxes are $ 200
and
Please type in the taxable income: 30000
Taxes are $ 650

Block Scope

All statements within a compound statement constitute a single block of code, and any variable declared within such a block only is valid within the block.
The location within a program where a variable can be used formally referred to as the scope of the variable.
Example:
{ // start of outer block
int a = 25;
int b = 17;
cout << “The value of a is “ << a
<< “ and b is “ << b << endl;
{ // start of inner block
float a = 46.25;
int c = 10;
cout << “ a is now “ << a
<< “b is now “ << b
<< “ and c is “ << c << endl;
}
cout << “ a is now “ << a
<< “b is now “ << b << endl;
} // end of outer block
The output is
The value of a is 25 and b is 17
a is now 46.25 b is now 17 and c is 10
a is now 25 b is now 17

One-way Selection

A useful modification of the if-else statement involves omitting the else part of the statement. In this case, the if statement takes a shortened format:
if (conditional expression) {
statements;
}
The flow chart of one-way if statement is as below.
Figure 7: Flowchart of statement

Example

The following program displays an error message for the grades that is less than 0 or more than 100.
#include <iostream.h>
int main()
{
int grade;
cout << "\nPlease enter a grade: ";
cin >> grade;
if(grade < 0 || grade > 100)
cout << " The grade is not valid\n";
return 0;
}

Nested If Statement

An if-else statement can contain simple or compound statements. Any valid C++ statement can be used, including another if-else statement. Thus, one or more if-else statements can be included within either part of an if-else statement. The inclusion of one or more if statement within an existing if statement is called a nested if statement.

The if-else Chain

When an if statement is included in the else part of an existing if statement, we have an if-else chain.
if (expression-1)
statement-1
else if (expression-2)
statement-2
else
statement-3

Example

The following program calculates the monthly income of a computer salesperson using the following commission schedule:
Figure 8: Layout of result
#include <iostream.h>
#include <iomanip.h>
int main()
{
float monthlySales, income;
cout << "\nEnter the value of monthly sales: ";
cin >> monthlySales;
if (monthlySales >= 50000.00)
income = 375.00 + .16 * monthlySales;
else if (monthlySales >= 40000.00)
income = 350.00 + .14 * monthlySales;
else if (monthlySales >= 30000.00)
income = 325.00 + .12 * monthlySales;
else if (monthlySales >= 20000.00)
income = 300.00 + .09 * monthlySales;
else if (monthlySales >= 10000.00)
income = 250.00 + .05 * monthlySales;
else
income = 200.00 + .03 * monthlySales;
// set output format
cout << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint)
<< setprecision(2);
cout << "The income is $" << income << endl;
return 0;
}
The output of the program:
Enter the value of monthly sales: 36243.89
The income is $4674.27

The Switch Statement

The switch statement controls program flow by executing a set of statements depending on the value of an expression.
Note: The value of expression must be an integer data type, which includes the char, int, long int, and short data types.
The syntax for the switch statement:
switch(expression){
case label:
statement(s);
break;
case label;
statement(s);
break;
default:
statement(s);
}
The expression in the switch statement must evaluate to an integer result. The switch expression’s value is compared to each of these case values in the order in which these values are listed until a match is found. When a match occurs, execution begins with the statement following the match.
If the value of the expression does not match any of the case values, no statement is executed unless the keyword default is encountered. If the value of the expression does not match any of the case values, program execution begins with the statement following the word default.
The break statement is used to identify the end of a particular case and causes an immediate exit from the switch statement. If the break statements are omitted, all cases following the matching case value, including the default case, are executed.
Example
#include <iostream.h>
int main()
{
int iCity;
cout << "Enter a number to find the state where a city is located. "<< endl;
cout << “1. Boston” << endl;
cout << "2. Chicago" << endl;
cout << "3. Los Angeles” << endl;
cout << "4. Miami” << endl;
cout << "5. Providence” << endl;
cin >> iCity;
switch (iCity)
{
case 1:
cout << "Boston is in Massachusetts " << endl;
break;
case 2:
cout << "Chicago is in Illinois " << endl;
break;
case 3:
cout << "Los Angeles is in California " << endl;
break;
case 4:
cout << "Miami is in Florida " << endl;
break;
case 5:
cout << "Providence is in Rhode Island " << endl;
break;
default:
cout << “You didn’t select one of the five cities” << endl;
} // end of switch
return 0;
}
The output of the above program:
Enter a number to find the state where a city is located.
1. Boston
2. Chicago
3. Los Angeles
4. Miami
5. Providence
3
Los Angeles is in California
The switch statement is a clean way to implement multi-way selection (i.e., selecting from among a number of different execution paths), but it requires an expression that evaluates to an integral value at compile-time.
When writing a switch statement, you can use multiple case values to refer to the same set of statements; the default label is optional. For example, consider the following example:
switch(number)
{
case 1:
cout << “Have a Good Morning\n”;
break;
case 2:
cout << “Have a Happy Day\n”;
break;
case 3:
case 4:
case 5:
cout << “Have a Nice Evening\n”;
}

The Enum Specifier

An enumerated data type is a way of attaching names to numbers, thereby giving
more meaning to anyone reading the code. The enum specifier creates an enumerated data type, which is simply a user-defined list of values that is given its own data type name. Such data types are identified by the reserved word enum followed by an optional user-selected name for the data type and a listing of acceptable values for the data type.
Example:
enum day { mon, tue, wed, thu, fri, sat, sun};
enum color {red, green, yellow};
Any variable declared to be of type color can take only a value of red or green or yellow. Any variable declared to be of type day can take only a value among seven given values.
The statement
enum day a, b,c;
declares the variables a, b, and c to be of type day.
Internally, the acceptable values of each enumerated data type are ordered and assigned sequential integer values beginning with 0. For example, for the values of the user-defined type color, the correspondences created by the C++ compiler are that red is equivalent to 0, green is equivalent to 1, and yellow is equivalent to 2. The equivalent numbers are required when inputting values using cin or displaying values using cout.

Example

#include <iostream.h>
int main()
{
enum color{red, green, yellow};
enum color crayon = red;
cout << “\nThe color is “ << crayon << endl;
cout << “Enter a value: “;
cin >> crayon;
if (crayon == red)
cout << “The crayon is red.” << endl;
else if (crayon == green)
cout << “The crayon is green.” << endl;
else if (crayon== yellow)
cout << “The crayon is yellow.” << endl;
else
cout << “The color is not defined. \n” << endl;
return 0;
}
The output of the above program:
The color is 0
Enter a value: 2
The crayon is yellow.

Focus on Problem Solving

Two major uses of C++’s if statements are to select appropriate processing paths and to prevent undesirable data from being processed at all. In this section, an example of both uses is provided.
Problem: Solving Quadratic Equations
A quadratic equation is an equation that has the form ax2 + bx + c = 0 or that can be algebraically manipulated into this form. In this equation, x is the unknown variable, and a, b and c are known constants. Although the constants b and c can be any numbers, including 0, the value of the constant a cannot be 0 (if a is 0, the equation becomes a linear equation in x). Examples of quadratic equations are:
5x^2 + 6x + 2 = 0
x^2 - 7x + 20 = 0
34x^2 + 16 = 0
In the first equation, a = 5, b = 6, and c = 2; in the second equation, a = 1, b = -7, and c = 20; and in the third equation, a = 34, b = 0 and c = 16.
The real roots of a quadratic equation can be calculated using the quadratic formula as:
delta = b2 – 4ac
root1 = (-b + squared-root(delta))/(2a)
root2 = (-b - squared-root(delta))/(2a)
Using these equations, we will write a C++ program to solve for the roots of a quadratic equation.

Step 1: Analyze the Problem

The problem requires that we accept three inputs – the coefficients a, b and c of a quadratic equation – and compute the roots of the equation using the given formulas.

Step 2: Develop a Solution

A first attempt at a solution is to use the user-entered values of a, band c to directly calculate a value for each of the roots. Thus, our first solution is:
Display a program purpose message.
Accept user-input values for a, b, and c.
Calculate the two roots.
Display the values of the calculated roots.
However, this solution must be refined further to account for a number of possible input conditions. For example, if a user entered a value of 0 for both a and b, the equation is neither quadratic nor linear and has no solution (this is referred to as a degenerate case).
Another possibility is that the user supplies a nonzero value for b but make a 0. In this case, the equation becomes a linear one with a single solution of –c/b. A third possibility is that the value of the term b^2 – 4ac, which is called the discriminant, is negative. Since the square root of a negative number cannot be taken, this case has no real roots. Finally, when the discriminant is 0, both roots are the same (this is referred to as the repeated roots case).
Taking into account all four of these limiting cases, a refined solution for correctly determining the roots of a quadratic equation is expressed by the following pseudocode:
Display a program purpose message.
Accept user-input values for a, b, and c.
If a = 0 and b = 0 then
Display a message saying that the equation has no solution.
Else if a = 0 then
calculate the single root equal to –c/b.
display the single root.
Else
Calculate the discriminant.
If the discriminant > 0 then
Solve for both roots using the given formulas.
Display the two roots.
Else if the discriminant < 0 then
Display a message that there are no real roots.
Else
Calculate the repeated root equal to –b/(2a).
Display the repeated root.
Endif.
Endif.
Notice in the pseudocode that we have used nested if-else structures. The outer if-else structure is used to validate the entered coefficients and determine that we have a valid quadratic equation. The inner if-else structure is then used to determine if the equation has two real roots (discriminant > 0), two imaginary roots (discriminant < 0) or repeated roots (discriminant =0).

Step 3 : Code the Algorithm

The equivalent C++ code corresponding to our pseudocode is listed as the following program
// This program can solve quadratic equation
#include <iostream.h>
#include <math.h>
#include <iomanip.h>
int main()
{
double a, b, c, del, x1, x2;
cout << “This program calculates the roots of a\n”;
cout << “ quadratic equation of the form\n”;
cout << “ 2\n”;
cout << “ ax + bx + c = 0\n\n”;
cout << “Enter values for a, b, and c: “;
cin >> a >> b >> c;
if ( a == 0.0 && b == 0.0)
cout << “The equation is degenerate and has no roots.\n”;
else if (a == 0.0)
cout << “The equation has the single root x = “
<< -c/b << endl;
else
{
del = b*b – 4.0*a*c;
if (del > 0.0)
{
x1 = (-b + sqrt(del))/(2*a);
x2 = (-b – sqrt(del))/(2*a);
cout << "The two roots are “
<< x1 << “ and “ << x2 << endl;
}
else if (del <0)
cout << "Both roots are imaginary.\n";
else
cout << “Both roots are equal to “ << -b/(2*a) << endl;
}
return 0;
}

Step 4: Test and Correct the Program

Test values should include values for a, b and c that result in two real roots, plus limiting values for a and b that result in linear equation (a = 0, b != 0), a degenerate equation ( a = 0, b = 0), and a negative and 0 discriminant. Two such test runs of the above program follow:
This program calculates the roots of a
quadratic equation of the form
ax^2 + bx + c = 0
Please enter values for a, b and c: 1 2 -35
The two real roots are 5 and –7
and
This program calculates the roots of a
quadratic equation of the form
ax^2 + bx + c = 0
Please enter values for a, b and c: 0 0 16
This equation is degenerate and has no roots.
We leave it as an exercise to create test data for the other limiting cases checked for by the program.

Comments, questions, feedback, criticisms?

Send feedback