Lesson 4 COMP218

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Lesson 4: Selection

Slide 1: Lesson Outline


This document is designed to help you take notes while watching the videos for this
lesson. Print these slides before going to the Video Lectures.
Note: Reviewing this material is not sufficient to fully understand the topic; you should
also complete the readings and exercises.
Review these slides

Logical Operators (slides 2-6)

Statements (slides 7-9)

Flowcharts (slides 10-11)

One-Way (If) Selection(slides 12-20)

Two-Way (If...Else) Selection (slides 21-26)

Multiple Selection (Nested If) (slides 27-31)

Review (slides 32-46)

Switch (slides 47-59)


Boolean Data Type (slides 60-63)

Lesson 4

Slide 2: Logical Operators


Selection

Selection statement allows the program to make a choice, that is to perform a test and

then to take the appropriate course of action.


Example:
- If I have $1.25, I will buy a coffee.
- If the light is green, I will cross the street.

Slide 3: Logical Operators


Selection (cont'd)
To test for a condition, you need relational operators.
Mathematical

C++

==

!=

<

<

<=

>

>

>=

Lesson 4

Slide 4: Logical Operators


Logical Expressions

What am I testing for?


age <18
answer == 'Y'
answer != 'Y'
n%2 == 0

What happens in this case?


int k;
double d;
...
k >= d // comparing an int to a double...

Slide 5: Logical Operators


Precedence of Operators
Logical Operators
English

Lesson 4

C++

NOT

AND

&&

OR

||

Priority
1
2
3

Precedence from Highest to Lowest


!*, /, %
+, <, <=, >, >=
==, !=

Logical NOT and unary Multiplication and division


Addition and subtraction
Logical comparisons
Logical equal & not-equal

&&

Logical AND

||

Logical OR

Slide 6: Logical Operators


Precedence Operators (cont'd)
Examples:
!, *, /, %
+, <, <= , >, >=
==, !=
&&
||
1) 10 % 4 * 3 - 8 <= 18 + 30 / 4 - 20
2) (3 < 5) || (21 <= 18) && (-81 > 0)

Check video for answers.

Lesson 4

Slide 7: Statements
Logical Statements
Example 1:
0 x 1 is written
0 <= x && x <= 1
0.0 <= x && x <= 1.0
Example 2:
The following are equivalent
!(age < 18) && !(age > 65)
age >= 18 && age <= 65
!(age < 18 || age > 65)

Slide 8: Statements
Logical Statements (cont'd)
Write logical expressions that correspond to each phrase:
1) integers a, b, c are all even.
2) at least one of integers a, b, c is even.
3) neither integer m nor n are odd.
4) both real number x and y are positive.
Check video for answers.

Lesson 4

9: Statem
ments
al Statements (con
nt'd)
gical expresssions that correspond
d to each phrase:
a digit charracter (i.e. ch is '0', '1'', ..., '9').
not a lowerr-case charracter.
xactly one of
o the real numbers
n
x and
a y is po
ositive.

10: Flowc
chart
hart is a gra
aphical way
y of represe
enting an allgorithm.
he following symbols:

11: Flowc
chart
le:
e and write
e out to scre
een the ave
erage of 3 g
grades. Pro
ompt user ffor 3 gradess.
video fo
or answer
r.

Slide 12: One-Way (If) Selection


Form:

if (condition) action statement


or

if (condition)
action statement
Example 1:
if (age >= 18) cout << "may vote";

Example 2:
if (month == 4)
days_in_month = 30;

Check video for answers.

Lesson 4

13: One-W
Way (If) Selection
n
hart

ndition is first
f
tested.
esult is true, statemen
nt
f the loop) is executed
d;
se, program
m control pa
asses to the
e
atement.

dition is giv
ven as a log
gical
on and must be includ
ded in
eses.

14: One-W
Way (If) Selection
n
le 3:
+ y > 8) cout <<
< count +=
+ 1;
< count;
n x = 5, y = 2 and cou
unt = 31, what
w
will be
?
n x = 5, y = 12 and co
ount = 31, what
w
will bee
?

or answer
rs.
video fo

Slide 15: One-Way (If) Selection


Example 4:
if (score >79 && score < 90) cout << "You get a B";
cout << "Congratulations!!!";

Slide 16: One-Way (If) Selection


Blocked One-Way Selection
If you want to perform more than one action, when the condition is met, you need to
block the action statements using { } .
Example 1a)
cout <<
"Number
please: ";
cin >> num;
if (num >
100)
{
cout <<
"That is a
big number!";
num = 0;
}
General syntax:

if (condition)
{

action statement 1
action statement 2
...
action statement n
}

Lesson 4

17: One-W
Way (If) Selection
n
ed One-W
Way Selec
ction (con
nt'd)
le 1b)
er please
e: ";
< "Numbe
> num;
um > 100)
ut << "T
That is a big num
mber!";
um = 0;

18: One-W
Way (If) Selection
n
ed One-W
Way Selec
ction (con
nt'd)
ng content of
o two varia
ables. How??

10
0

Slide 19: One-Way (If) Selection


Blocked One-Way Selection (cont'd)
Example 2:
Inputs two integers, output them in increasing order.
int x,y;
cout << "Enter two integers:";
cin >> x >> y;
if (x > y)
{
// swap the contents of x & y
int temp = x; // local variable
x = y;
y = temp;
}
cout << x << "<=" << y << endl;

Slide 20: One-Way (If) Selection


Block Statements in General
Rules:
A block may contain declarations.

Form:

{
statement 1
statement 2
...
statement n
}

A block is considered a statement


and can
occur anywhere a single statement
can be used.

A block is treated as a single unit.

Use indenting to increase program


readability.

Lesson 4

11

21: Two-W
Way (If...Else) Se
election

dition)
entT
entF

:
ondition is met, action
n statementtT is executted, otherw
wise
entF is executed.
22: Two-W
Way (If...Else) Se
election
le 1:
% 2 == 0)
<< n << " is eve
en" << en
ndl;
d" << end
dl;
<< n << " is odd

12
2

Slide 23: Two-Way (If...Else) Selection


Example 2:
This program prints the minimum of two integers.
int main()
{ int m, n;
cout << "Enter two integers: ";
cin >> m >> n;
if (m < n)
cout <<m<< " is the minimum.\n";
else
cout <<n<< " is the minimum.\n";
return 0;
}

Slide 24: Two-Way (If...Else) Selection


Example 3:
User friendly input.
int main()
{
char ans;
cout << " Are you enrolled (y/n)?";
cin >> ans;
if (ans=='y' || ans=='Y')
cout << "You are enrolled.\n";
else
cout << "You are not enrolled.\n";
return 0;
}

Lesson 4

13

Slide 25: Two-Way (If...Else) Selection


Blocked Two-Way Selection
Example 1:
A discount is given for purchases of at least five base balls. We wish to output the cost
as well as a message indicating whether a discount was given.
if (number >=5)
{
cout << "Discount\n";
cost = 10 * number;
}
else
{
cout << "No Discount\n";
cost = 12 * number;
}
cout << "Cost of your order is: " << cost << endl;

Slide 26: Two-Way (If...Else) Selection


Blocked Two-Way Selection (cont'd)
What happens if you omit braces?
if ((carDoors == 4 ) && (driverAge > 24))
premium = 650.00;
cout << " LOW RISK ";
else
premium = 1200.00 ;
cout << " HIGH RISK" ;
monthlyPayment = premium / 12.0 + 5.00 ;
COMPILE ERROR OCCURS.
The "if clause" is the single statement following the if.

Lesson 4

14

Slide 27: Multiple Selection

There are situations where decisions are made on more than two alternatives.

Need a Nested else-if Statement.

Multiple selection combines the "else" and following "if " condition on a single line.

Slide 28: Multiple Selection


Example 1:
The integer n can be strictly positive (> 0), zero or negative (< 0).
if (n < 0)
cout << n << " is negative";
else if
(n == 0)
cout << n << " is zero";
else
cout << n << " is strictly positive";

Lesson 4

15

Slide 29: Multiple Selection


Form:
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
...
else
statementn
Action:
1) Select among the alternatives condition1,
condition2, condition3, ..., conditionn.
2) If condition1 is true, execute statement1.
Otherwise, if condition2 is true, execute
statement2.
Otherwise (if conditionn is true), execute
statementn.
3) Once a statement is executed, program
control passes to the next statement
after the alternative conditions.

Lesson 4

16

Slide 30: Multiple Selection


Two Ways to Solve a Same Problem
We want to find the minimum of three numbers.
Version 1
void main()
{ int n1, n2, n3;
cout << "Enter three integers: ";
cin >> n1 >> n2 >>n3;
int min = n1;
if (n2 < min) min = n2;
if (n3 < min) min = n3;
cout << "Their minimum is " << min << endl;
}

Slide 31: Multiple Selection


Two Ways to Solve a Same Problem (cont'd)
We want to find the minimum of three numbers.
Version 2
void main()
{
int n1, n2, n3;
cout << "Enter three integers: " ;
cin >> n1 >> n2 >>n3;
cout << "The minimum is " ;
if (n1 <= n2 && n1 <= n3)
cout << n1 << endl;
if (n2 <= n1 && n2 <= n3)
cout << n2 << endl;
if (n3 <= n1 && n3 <= n2)
cout << n3 << endl;
}

Note : This version is not as "efficient" as version 1. It is used to illustrate compound


conditions.

Lesson 4

17

Slide 32: Review


Exercise 1:
The following program prompts for inputs hours and rate, then outputs either an error
message or the employee's wage.
1) Give the output when inputs for hours and rate are:
a) -5 and 8.50
b) 50 and 100
c) 10 and 3.50
2) Describe in words the way an employee is compensated for overtime.
Check video for answers.

Slide 33: Review


#include <iostream>
using namespace std;
const float MIN_WAGE = 7.75;
int main()
{
int hours;
float rate, wages;
cout << "Enter hours worked & hourly rate: ";
cin >> hours >> rate;
if (hours >= 0 && rate >= MIN_WAGE)
{// valid inputs for hours and wages
if (hours <= 40)
wages = hours * rate;
else
wages = 40 * rate +(hours - 40) * 2.0* rate;
cout << "Wages = $" << setprecision(2) << wages << endl;
}
else //hours and/or rate invalid
cerr << "INPUT ERROR(S).\n"; // NEW!!! Sends output
immediately
return 0;
}

Lesson 4

18

Slide 34: Review


int hours;
float rate, wages;
cout << "Enter hours worked & hourly rate:";
cin >> hours >> rate;
if (hours >= 0 && rate >= MIN_WAGE)
{ // valid inputs for hours and wages
if (hours <= 40)
wages = hours * rate;
else
wages = 40 * rate +(hours - 40) * 2.0* rate;
cout << "Wages = $" << setprecision(2) << wages << endl;
}
else //hours and/or rate invalid
cerr << "INPUT ERROR(S).\n" ; // NEW!!! Sends output
immediately

Slide 35: Review


MIN_WAGE
7.75

Hours
-5

Rate
8.50

cout << "Enter hours worked & hourly rate: ";


cin >> hours >> rate;
if (hours >= 0 && rate >= MIN_WAGE)
{ // valid inputs for hours and wages
if (hours <= 40)
wages = hours * rate;
else
wages = 40 * rate +(hours - 40) * 2.0* rate;
cout << "Wages = $" << setprecision(2)
<< wages << endl;
}
else //hours and/or rate invalid
cerr << "INPUT ERROR(S).\n"; // NEW!!!
// Sends output immediately

Lesson 4

19

Slide 36: Review


MIN_WAGE
7.75

Hours
50

Rate
100

cout << "Enter hours worked & hourly rate: ";


cin >> hours >> rate;
if (hours >= 0 && rate >= MIN_WAGE)
{ // valid inputs for hours and wages
if (hours <= 40)
wages = hours * rate;
else
wages = 40 * rate +(hours - 40) * 2.0* rate;
cout << "Wages = $" << setprecision(2)
<< wages << endl;
}
else //hours and/or rate invalid
cerr << "INPUT ERROR(S).\n"; // NEW!!!
// Sends output immediately

Lesson 4

20

Slide 37: Review


MIN_WAGE
7.75

Hours
10

Rate
3.50

cout << "Enter hours worked & hourly rate: ";


cin >> hours >> rate;
if (hours >= 0 && rate >= MIN_WAGE)
{ // valid inputs for hours and wages
if (hours <= 40)
wages = hours * rate;
else
wages = 40 * rate +(hours - 40) * 2.0* rate;
cout << "Wages = $" << setprecision(2)
<< wages << endl;
}
else //hours and/or rate invalid
cerr << "INPUT ERROR(S).\n"; // NEW!!!
// Sends output immediately

Slide 38: Review


Exercise 2:
A university student is awarded a letter grade based on the following criteria:
Range

Letter

100 - 90

89 - 80
79 - 70
69 - 0

B
C
F

Write a nested if statement that takes the number grade and outputs the equivalent
letter grade.

Lesson 4

21

Slide 39: Review


Exercise 2: (Approach 1)
Exercise 2: (Approach 2)
Range
100 - 90
89 - 80
79 - 70
69 - 0

Letter
A
B
C
F

Check video for answers.

Slide 40: Review


Two-Way Selection
Exercise 1:
The following program fragment is written in poor style. Explain what is wrong and
rewrite it.
if (age
cout
if (age
cout

>= 65)
<< "You can retire!";
< 65)
<< "Keep working";

Check video for answers.

Lesson 4

22

Slide 41: Review


Two-Way Selection (cont'd)
Exercise 2:
Find the error(s) in the following code.
if (age >= 18);
cout << "You may vote!";
else
cout << "Too young to vote";

Slide 42: Review


Two-Way Selection (cont'd)
Exercise 3:
Give the output of the following program fragment when yr is 1995, 1996, 1900, 100.
if (yr%4==0 && (yr%400==0 || yr%100 != 0))
cout << " leap year\n";
else
cout << " not leap year\n";

Slide 43: Review


Nested If/Else
Exercise 1:
Improve the efficiency and style of the following program segment.
if (age>=18 && gender == 'F') cout << "Adult female";
if (age>=18 && gender == 'M') cout << "Adult male";
if (age<18 && gender == 'F') cout << "Juvenile female";
if (age<18 && gender == 'M') cout << "Juvenile male";
Check video for answer.

Lesson 4

23

Slide 44: Review


Nested If/Else (cont'd)
Exercise 2:
Objects n and m are integers. After input of n, m is assigned a value that depends on n
as follows:

n is 1:
n is 3:
n is 4:
n is 7:
all other values of n: m is 0

m is n
m is n*n
m is n*n*n
m is 1

Write a nested if/else sequence that assigns the value of m.

Slide 45: Review


The "Dangling" Else

A nested if statement begins with an outer control structure that is either a simple if
or an if/else statement.

Within the outer if statement are sub-statements that are themselves simple if or
if/else statements.

When combinations of if and if/else statements combine in a nested structure, it can


be difficult to keep straight the if-else pairings.

While indenting is important for program readability, it is not used by the compiler to
match the if and else statements.

Lesson 4

24

Slide 46: Review


The "Dangling" Else(cont'd)
Example:
Seniors are offered free checking accounts, while others are charged $0.25/check. All
customers pay $20.00 for an overdraft.
Output for the folowing cases?
CheckAmount
$100.00
$100.00
$200.00
$200.00

AccBalance IsSenior
$200.00
$200.00
$100.00
$100.00

true
false
true
false

// declare object with initial charge set to 0.0


double checkAmount, checkCharge=0.0, acctBalance;
bool isSenior;
. . .
// check for sufficient funds
if (checkAmount <=acctBalance)
// non seniors pay $0.25/check
if (!isSenior)
checkCharge=0.25;
else
// with insufficient funds, all charged $20.00
checkCharge=20.00;
cout << "Check Charge is " << checkCharge;

Lesson 4

25

Slide 47: Switch


Statement
Example 1 (version 1):
Using nested if statements.
char romanNumeral;
int decValue;
if (romanNumeral == 'I')
decValue = 1;
else if (romanNumeral == 'V')
decValue = 5;
else if (romanNumeral == 'X')
decValue = 10;
else if (romanNumeral == 'L')
decValue = 50;
else if (romanNumeral == 'C')
decValue = 100;
else
cout << "Not a Roman numeral <= 100";
Switch statement provides a cleaner way to do multiway selection than the more
general nested if.

Lesson 4

26

Slide 48: Switch


Statement (cont'd)
Example 1 (version 2):
Using a switch statement.
char romanNumeral; int decValue;
switch (romanNumeral)
// romanNumeral is selector expression
{
case 'I': decValue = 1;
break;
case 'V': decValue = 5;
break;
case 'X': decValue = 10;
break;
case 'L': decValue = 50;
break;
case 'C': decValue = 100;
break;
default : cout << "Not a Roman numeral<= 100";
}

Slide 49: Switch


Statement (cont'd)
Form:
switch (selector-expression)
{
case constant 1: statement(s)
break;
case constant 2: statement(s)
break;
. . .
case constant n: statement(s)
break;
default:
default-statement
} // end switch

Lesson 4

27

Slide 50: Switch


Statement (cont'd)

The selector expression and the constants must be of the same ordinal type. This
includes integers, character, bool (and enumerated types).

The break statement is necessary to tell the system to "break" out of the switch
statement.

You need not have a default section. If no matches are found, then nothing happens
when the switch statement is executed.

Slide 51: Switch


Statement (cont'd)
Example 2:
Write a switch statement that is equivalent to the following multiple selection
statement. Let object a be the switch selector.
if (a == 3)
result = a;
else if (a == 6)
result = a + 10;
else if (a == 10)
result = a + 20;
else
result = a + 30;

Lesson 4

28

Slide 52: Switch


Statement (cont'd)
Example 3:
What will this program segment output if the user types 5, 3 and 1?
cout << "Enter a positive integer";
cin >> num;
cout << "The Spanish word for " << num << "is";
switch (num)
{
case 1: cout << "uno";
case 2: cout << "dos";
case 3: cout << "tres";
default: cout << "???":
} // end switch statement
cout << ". " << endl;

Lesson 4

29

Slide 53: Switch


Statement (cont'd)
Example 4:
Listing cases with the same action together.
switch(month)
{
case 4: case 6: case 9: case 11:
cout << "30 days";
break;
case 3: case 5: case 7:
case 8: case 10: case 12:
cout << "31 days";
break;
case 2: cout << "28 or 29 days";
break;
default: // invalid month
cout << "Invalid value for month";
} // end switch

Slide 54: Switch


If-Then-Else for a Mail Order
Write a program segment which will:

Assign value .25 to discountRate and assign value 10.00 to shipCost if purchase is
over 100.00;

Otherwise, assign value .15 to discountRate and assign value 5.00 to shipCost;

Either way, calculate totalBill.

Lesson 4

30

Slide 55: Switch


If-Then-Else for a Mail Order (cont'd)
if (purchase > 100.00)
{
discountRate = .25;
shipCost = 10.00;
}
else
{
discountRate = .15;
shipCost = 5.00;
}
totalBill = purchase * (1.0 - discountRate) + shipCost;

Slide 56: Switch


If-Then-Else for a Mail Order (cont'd)
1) If taxCode is 'T', increase price by adding taxRate times price to it.
2) If code has value 1, read values for income and taxRate and calculate and display
taxDue as their product.
3) If A is strictly between 0 and 5, set B equal to 1/A. Otherwise, set B equal to A.
Check video for answers.

Lesson 4

31

Slide 57: Switch


What Output and Why?
int age;
age = 20;
// Warning.
if ( age = 16 )
{
cout << "Did you get your driver's license?";
}

int age;
age = 30;
if ( age < 18 )
cout << "Do you drive?";
cout << "Too young to vote";

Slide 58: Switch


What Output and Why?
int number;
number = 0;
if ( number == 0 )
cout << "Zero value";
else
cout << "Non-zero value";

Slide 59: Switch


Writing Nested if Statements
Your city classifies a pollution index:

Less than 35 as "Pleasant"

35 through 60 as "Unpleasant"

Above 60 as "Health Hazard"

Display the correct description of the pollution index value.


Check video for answer.
Lesson 4

32

Slide 60: Boolean Data Type

An object of Boolean type has only two values: false or true.

The type is bool.

Declaration/initialization:
bool valid;
bool isOver18 = true

Slide 61: Boolean Data Type


Example 1:
bool valid;
char ans;
cout << "(Y)es or (N)o?";
cin >> ans;
valid = ans == 'Y' || ans == 'N';
if (valid)
else
cout << "Your answer is valid";
cout << "That is an incorrect choice";

Slide 62: Boolean Data Type


Example 2:
The following logical expressions assign a value to bool object boolValue. Give values
for p, q, and r (where appropriate) that would result in boolValue having the specified
value.
a) boolValue = !p || q; boolValue = false
b) boolValue = p && !q; boolValue = true
c) boolValue = p && (q || !r); boolValue = true

Lesson 4

33

Slide 63: Boolean Data Type


Example 3:
Each of the following situations involves logical expressions. Declare objects that serve
as operands for the expression and a bool object whose name describes the
expressions. Give the expression:
a) An SUV is said to be fuel efficient if its km per liter in the city is at least 12.
b) In the region, normal rainfall total is in the range 9.0 <= rain < 14.0.

Lesson 4

34

You might also like