Chapter 3
Chapter 3
Chapter 3
Making Decision
Outline
Relational Operations
If statement
If
If/else statement
If/else if
Logical operators
Switch
Relational Operators
Relational operations allow you to compare numeric and
char values and determine whether one is greater, less, equal
to, or not equal to another.
Operators:
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Slide 4- 3
Relational Expressions
Boolean expressions – true or false
Examples:
12 > 5 is true
7 <= 5 is false
if x is 10, then
x == 10 is true,
x != 8 is true, and
x == 8 is false
Slide 4- 4
int x, y ;
x = 4;
y = 6;
EXPRESSION VALUE
x<y
x+2<y
x != y
x + 3 >= y
y == x
y == x+2
y=x+3
int x, y ;
x = 4;
y = 6;
EXPRESSION VALUE
x<y true
x+2<y false
x != y true
x + 3 >= y true
y == x false
y == x+2 true
y=x+3 7
Relational Expressions
Slide 4- 7
Like all C++ expressions,
relational expressions are
evaluated to yield a numerical result.
A condition that we would interpret as true
evaluates to an integer value of 1;
a false condition results in an integer value of 0.
Samples:
cout << (3 < 4) << endl;
cout << (2.0 > 3.0);
Results:
1
0
Slide 4- 8
Outline
Relational Operations
If statement
If
If/else statement
If/else if
Logical operators
Switch
if statement
Select whether or not to execute a statement (which can
be a single statement or an entire block) without the
else clause
TRUE
expression
FALSE statement
Flowchart for Evaluating a Decision
Slide 4- 13
The if Statement
General Format:
if (expression)
statement;
Slide 4- 14
Example: Check a Car’s Mileage
#include <iostream>
int main ()
{
double LIMIT = 30000.0; //set car mileage limit
double mileage = 0.0; //stores mileage entered by user
cout << "Please enter the mileage recorded on the car: ";
cin >> mileage;
End of program.
End of program.
(Program Continues)
Slide 4- 17
Slide 4- 18
Flowchart for Lines 21 and 22
Slide 4- 20
if statement notes
Do not place ; after (expression)
Place statement; on a separate line
after (expression), indented:
if (score > 90)
grade = 'A';
Be careful testing floats and doubles
for equality
0 is false; any other value is true
Slide 4- 21
Expanding the if Statement
To execute more than one statement as part of an if
statement, enclose them in { }:
if (score > 90)
{
grade = 'A';
cout << "Good Job!\n";
}
Slide 4- 22
Outline
Relational Operations
If statement
If
If/else statement
If/else if
Logical operators
Switch
if-else provides two-way selection between executing one of 2 clauses:
the if clause or the else clause
FALSE TRUE
expression
• General Format:
if (expression)
statement1; // or block
else
statement2; // or block
Slide 4- 25
Use of blocks recommended
if ( expression )
{
“if clause”
}
else
{
} “else clause”
A compound statement consists of
individual statements enclosed within braces.
Syntax:
if(expression)
{
statement1;
statement2;
statement3;
}
else
{
statement4;
statement5;
statement6;
}
Slide 4- 29
Exercise: mail order
Assign value .25 to discount_rate and assign value 10.00 to
ship_cost if purchase is over 100.00
Relational Operations
If statement
If
If/else statement
If/else if
Logical operators
Switch
if/else if format (if-else chain or extended if-
else)
Using nested if statements
if ( Expression1 )
Statement1
else if ( Expression2 )
Statement2
.
.
. EXACTLY 1 block of these
else if ( ExpressionN ) statements will be executed.
StatementN
else
Statement N+1
Used when only one condition
can be true
Example
Marital Status Input Code
Married M
Single S
Divorce D
Widowed W
Example
int main ( void )
{
char marital_status; //marital status code entered by user
//Prompt user for marital status code
cout << "Enter a marital code: " << endl;
cin >> marital_status;
//Displays marital status message
if (marital_status == 'M')
cout <<"Individual is married." << endl;
else if (marital_status == 'S')
cout <<"Individual is single." << endl;
else if (marital_status == 'D')
cout <<"Individual is divorced." << endl;
else if (marital_status == 'W')
cout <<"Individual is widowed." << endl;
else
cout << "An invalid code was entered." << endl; //used as error message
return 0;
}
Output (Test all possible paths):
Enter a marital code:
D
Individual is divorced.
Enter a marital code:
S
Individual is single.
Enter a marital code:
M
Individual is married.
Enter a marital code:
W
Individual is widowed.
Enter a marital code:
m
An invalid code was entered. //results in an error message
Exercise: extended if statement (if-else chain):
Less than $50,000 but greater than or equal to $350 plus 14% sales
$40,000
Less than $40,000 but greater than or equal to $325 plus 12% sales
$30,000
Less than $30,000 but greater than or equal to $300 plus 9% sales
$20,000
Less than $20,000 but greater than or equal to $250 plus 5% of sales
$10,000
Less than $10,000 $200 plus 3% of sales
Slide 4- 39
//Calculates salesperson's income
if(monthly_sales >= 50000.00)
income = 375.00 + .16 * monthly_sales;
else if(monthly_sales >= 40000.00)
income = 350.00 + .14 * monthly_sales;
else if(monthly_sales >= 30000.00)
income = 325.00 + .12 * monthly_sales;
else if(monthly_sales >= 20000.00)
income = 300.00 + .09 * monthly_sales;
else if(monthly_sales >= 10000.00)
income = 250.00 + .05 * monthly_sales;
else income = 200.00 + .03 * monthly_sales;
Slide 4- 40
int main ( void )
{
//stores salesperson’s name, monthly sales and calculated income
double monthly_sales = 0.0, income = 0.0;
string salesperson_name;
//Prompts user for salesperson's name & sales
cout << "Please enter the saleperson's name: ";
getline(cin, salesperson_name);
cout << "Enter the value of monthly sales: " << endl;
cin >> monthly_sales;
//Calculates salesperson's income
if (monthly_sales >= 50000.00)
income = 375.00 + .16 * monthly_sales;
else if (monthly_sales >= 40000.00)
income = 350.00 + .14 * monthly_sales;
else if (monthly_sales >= 30000.00)
income = 325.00 + .12 * monthly_sales;
else if (monthly_sales >= 20000.00)
income = 300.00 + .09 * monthly_sales;
else if (monthly_sales >= 10000.00)
income = 250.00 + .05 * monthly_sales;
else income = 200.00 + .03 * monthly_sales;
//Displays salesperson's name & income
cout << setprecision(2) << fixed <<showpoint;
cout << salesperson_name << " has earned a total monthly income of $"
<< income << endl << " based on monthly sales of $" << monthly_sales;
return 0;
}
Outline
Relational Operations
If statement
If
If/else statement
If/else if
Logical operators
Switch
Boolean Expressions
3 Logical Operators
! && ||
LOGICAL
EXPRESSION MEANING DESCRIPTION
p || q p OR q p || q is true if either
p or q or both are true.
It is false otherwise.
Truth Table – Logical “AND”
X Y X && Y
TRUE TRUE
TRUE FALSE
FALSE TRUE
FALSE FALSE
Truth Table – Logical “AND”
X Y X && Y
TRUE TRUE TRUE
X Y X || Y
TRUE TRUE
TRUE FALSE
FALSE TRUE
FALSE FALSE
Truth Table – Logical “OR”
X Y X || Y
TRUE TRUE TRUE
X !X
TRUE
FALSE
Truth Table – Logical “not”
X !X
TRUE FALSE
FALSE TRUE
(x <= z) || (y == z)
(x <= z) || (y != z)
!(x >= z)
Logical Operators - examples
(x <= z) || (y == z) false
(x <= z) || (y != z) true
Slide 4- 58
Nested if statements
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.
Here, the else is paired with the inner if, which destroys the meaning of the
original if-else statement. Note also that the indentation is irrelevant as far
as the computer is concerned. Whether the indentation exists or not,
the statement is compiled by associating the last else with the closest
unpaired if, unless braces are used to alter the default pairing.
The process of nesting if statements can be extended indefinitely,
so the cout << “snap”; statement could itself be replaced by either
a complete if-else statement or another one-way if statement.
Slide 4- 60
Outline
Relational Operations
If statement
If
If/else statement
If/else if
Logical operators
Switch
Multi-alternative Selection
is also called multi-way branching, and
can be accomplished by one of two methods:
Using sequential if statements
if ( Expression1 )
Statement1;
if ( Expression2 )
Statement2;
.
.
. One or more of these statements
if ( ExpressionN ) may be executed.
StatementN;
Used when more than one
condition can be true
Slide 4- 62
Slide 4- 63
switch statement format
switch (expression) //integer or character
{ // start of compound statement
case exp1: // terminate with a colon
statement1;
break;
case exp2: // terminate with a colon
statement2;
break;
...
case expn: // terminate with a colon
statementn;
break;
default: // terminate with a colon
statementn+1;
} //end of switch & compound statement
Slide 4- 67
switch statement
requirements
1) expression must be an integer variable or an
expression that evaluates to an integer value
2) exp1 through expn must be constant integer
expressions or literals, and must be unique in the
switch statement
3) default is optional but highly recommended
Slide 4- 68
switch statement – how it
works
1) expression is evaluated
2) The value of expression is compared against exp1
through expn.
3) If expression matches value expi, the program
branches to the statement following expi and continues
to the end of the switch
4) If no matching value is found, the program branches to the
statement after default:
Slide 4- 69
break statement
Slide 4- 70
Slide 4- 71
Slide 4- 72
Slide 4- 73
Slide 4- 74
Multiple case values
switch (number)
{
case 1:
cout << "Have a Good Morning" << endl;
break;
case 2:
cout << "Have a Happy Day" << endl;
break;
case 3: case 4: case 5:
cout << "Have a Nice Evening" << endl;
break;
}