chapter 4: making decisions. outline relational operations if statement – if – if/else statement...

67
Chapter 4: Making Decisions

Upload: andy-preston

Post on 14-Dec-2015

256 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Chapter 4:

Making Decisions

Page 2: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Outline

• Relational Operations• If statement

– If – If/else statement– If/else if

• Logical operators• Switch

Page 3: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 3

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

Page 4: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 4

Relational Expressions

• Boolean expressions – true or false• Examples:

12 > 5 is true7 <= 5 is falseif x is 10, then x == 10 is true, x != 8 is true, and x == 8 is false

Page 5: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

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

Page 6: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

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

Page 7: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 7

Relational Expressions

• Can be assigned to a variable:result = x <= y;

• By default, assigns 0 for false, 1 for true• Do not confuse = and ==• 0 is false; any other value is true

Page 8: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 8

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

Page 9: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Outline

• Relational Operations• If statement

– If – If/else statement– If/else if

• Logical operators• Switch

Page 10: Chapter 4: Making Decisions. 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

FALSE statement

expression

Page 11: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 13

Flowchart for Evaluating a Decision

Page 12: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 14

The if Statement

• General Format:

if (expression)statement;

• If the expression is true, then statement is executed.

• If the expression is false, then statement is skipped.

Page 13: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

#include <iostream>int main ( void ){ const 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; if (mileage > LIMIT) cout << "This car is over the limit.";

cout << "\n\nEnd of program."; return 0;}

Example: Check a Car’s Mileage

Page 14: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Example: Results

Output from first run:Please enter the mileage recorded on the car: 35620.8This car is over the limit.

End of program.

Output from second run:Please enter the mileage recorded on the car: 25620.3

End of program.

Page 15: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 17

(Program Continues)

Page 16: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 18

Page 17: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch
Page 18: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 20

Flowchart for Lines 21 and 22

Page 19: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 21

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

Page 20: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 22

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";

} • { } creates a block of code (like your main function)

Page 21: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Outline

• Relational Operations• If statement

– If – If/else statement– If/else if

• Logical operators• Switch

Page 22: Chapter 4: Making Decisions. 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

TRUEFALSE

if clauseelse clause

expression

Page 23: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 25

The if/else Statement

• Provides two possible paths of execution• Performs one statement or block if the expression is true, otherwise performs another statement or block.

• General Format:if (expression)

statement1; // or blockelse

statement2; // or block

Page 24: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Use of blocks recommended

if ( expression ){ }else{

}

“if clause”

“else clause”

Page 25: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 29

A compound statement consists of individual statements enclosed within braces.

Syntax:if(expression){ statement1; statement2; statement3;}else{ statement4; statement5; statement6;}

Page 26: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Exercise: mail orderAssign value .25 to discount_rate and assign value 10.00 to ship_cost if purchase is over 100.00

Otherwise, assign value .15 to discount_rate and assign value 5.00 to ship_cost

Either way, calculate total_bill

if(expression){ statement1; statement2; statement3;}else{ statement4; statement5; statement6;}

Page 27: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

These braces cannot be omitted

if ( purchase > 100.00 ){ discount_rate = .25 ;

ship_cost = 10.00 ;}else{

discount_rate = .15 ; ship_cost = 5.00 ;

}

total_bill = purchase * (1.0 – discount_rate) + ship_cost ;

Page 28: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

(Program Continues)

Page 29: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch
Page 30: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Outline

• Relational Operations• If statement

– If – If/else statement– If/else if

• Logical operators• Switch

Page 31: Chapter 4: Making Decisions. Outline 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

.

.

.else if ( ExpressionN )

StatementNelse

Statement N+1

EXACTLY 1 block of these statements will be executed.

Used when only one condition can be true

Page 32: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Example

Marital Status Input Code Married M Single S Divorce D Widowed W

Page 33: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Exampleint 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;}

Page 34: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

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

Page 35: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 39

Monthly Sales Income

Greater than or equal to $50,000 $375 plus 16% of sales

Less than $50,000 but greater than or equal to $40,000 $350 plus 14% sales

Less than $40,000 but greater than or equal to $30,000 $325 plus 12% sales

Less than $30,000 but greater than or equal to $20,000 $300 plus 9% sales

Less than $20,000 but greater than or equal to $10,000 $250 plus 5% of sales

Less than $10,000 $200 plus 3% of sales

Exercise: extended if statement (if-else chain):

Calculate the monthly income of a salesperson by using the following commission schedule:

Page 36: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 40

//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;

Page 37: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

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;}

Page 38: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Outline

• Relational Operations• If statement

– If – If/else statement– If/else if

• Logical operators• Switch

Page 39: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Simple boolean expression use relational and/or logical operators.

6 Relational (or comparison) Operators< <= > >= == !=

3 Logical Operators! && ||

Boolean Expressions

Page 40: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

LOGICAL EXPRESSION MEANING DESCRIPTION

! p NOT p ! p is false if p is true! p is true if p is false

p && q p AND q p && q is true ifboth p and q are true. It is false otherwise.

p || q p OR q p || q is true if eitherp or q or both are true.

It is false otherwise.

Page 41: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Truth Table – Logical “AND”

TRUE TRUE

TRUE FALSE

FALSE TRUE

FALSE FALSE

X Y X && Y

Page 42: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Truth Table – Logical “AND”

TRUE TRUE TRUE

TRUE FALSE FALSE

FALSE TRUE FALSE

FALSE FALSE FALSE

X Y X && Y

Page 43: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Truth Table – Logical “OR”

TRUE TRUE

TRUE FALSE

FALSE TRUE

FALSE FALSE

X Y X || Y

Page 44: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Truth Table – Logical “OR”

TRUE TRUE TRUE

TRUE FALSE TRUE

FALSE TRUE TRUE

FALSE FALSE FALSE

X Y X || Y

Page 45: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Truth Table – Logical “not”

TRUE

FALSE

X !X

Page 46: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Truth Table – Logical “not”

TRUE FALSE

FALSE TRUE

X !X

If the Boolean expression is true, the combined expression is false.

If the Boolean expression is false, the combined expression is true.

Page 47: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Logical Operators - examples

int x = 12, y = 5, z = -4; (x > y) && (y > z)

(x > y) && (z > y)

(x <= z) || (y == z)

(x <= z) || (y != z)

!(x >= z)

Page 48: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Logical Operators - examples

int x = 12, y = 5, z = -4;

(x > y) && (y > z) true

(x > y) && (z > y) false

(x <= z) || (y == z) false

(x <= z) || (y != z) true

!(x >= z) false

Page 49: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Write an expression for each• tax_rate is over 25% and income is less

than $20000(tax_rate > 0.25) && (income < 20000)

• temperature is less than or equal to 75 or humidity is less than 70%(temperature <= 75) || (humidity < .70)

• age is over 21 and age is less than 60(age > 21) && (age < 60)

• age is 21 or 22(age == 21) || (age == 22)

Page 50: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

ExampleThe extended if statement should be as follows to allow the user to enter

either uppercase or lowercase marital codes:

//Displays marital status message if (marital_status == 'M' || marital_status == 'm') cout <<"Individual is married." << endl; else if (marital_status == 'S' || marital_status == 's')

cout <<"Individual is single." << endl; else if (marital_status == 'D' || marital_status == 'd')

cout <<"Individual is divorced." << endl; else if (marital_status == 'W' || marital_status == 'w')

cout <<"Individual is widowed." << endl; else

cout << "An invalid code was entered." << endl;

Page 51: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 57

Logical Operators - notes

• ! has highest precedence, followed by &&, then ||

• If the value of an expression can be determined by evaluating just the sub-expression on left side of a logical operator, then the sub-expression on the right side will not be evaluated (short circuit evaluation)

• 3 logical operators order of precedence

! && ||

Page 52: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 58

As with all expressions, parentheses can be used to alter the assigned operator priority and to improve the readability of relational expressions. By evaluating the expressions within the parentheses first, we find that the following compound condition is evaluated as shown:

(6 * 3 == 36 / 2) || (13 < 3 * 3 + 4) && !(6 – 2 < 5) (18 == 18) || ( 13 < 9 + 4 ) && !( 4 < 5 ) 1 || (13 < 13) && !1 1 || 0 && 0 1 || 0 1

Page 53: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 59

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.

for statement1 in the if statement if ( hours < 9 ) statement1; else cout << “pop”; results in the nested if statement if ( hours < 9 ) { cout << “snap”;

if ( hours > 6 ) cout << “snap extra”; } else cout << “pop”;

Page 54: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 60

The braces around the inner one-way if are essential, because in their absence, C++ associates an else with the closest unpaired if. Thus, without the braces, the foregoing statement is equivalent to if ( hours < 9 ) if ( hours > 6 ) cout << “snap”; else cout << “pop”;

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.

Page 55: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Outline

• Relational Operations• If statement

– If – If/else statement– If/else if

• Logical operators• Switch

Page 56: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 62

Multi-alternative Selectionis also called multi-way branching, and

can be accomplished by one of two methods: Using sequential if statements

if ( Expression1 ) Statement1;

if ( Expression2 )Statement2;

.

.

.if ( ExpressionN )

StatementN;

One or more of these statements may be executed.

Used when more than one condition can be true

Page 57: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 63

Page 58: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 67

switch statement formatswitch (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

Page 59: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 68

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

Page 60: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 69

switch statement – how it works

1) expression is evaluated2) 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:

Page 61: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 70

break statement

• Used to exit a switch statement• Useful to execute a single case statement

without executing the statements following it• If it is left out, the program "falls through" the

remaining statements in the switch statement

• Used to stop execution in the current block

Page 62: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 71

Page 63: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 72

Page 64: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 73

Page 65: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Slide 4- 74

Page 66: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

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; }

We can use multiple case values to refer to the same set of statements; the default label is optional

Page 67: Chapter 4: Making Decisions. Outline Relational Operations If statement – If – If/else statement – If/else if Logical operators Switch

Character data types in “Switch” switch (choice) { case 'a': case 'e': case 'i': case 'o': case 'u': cout << "\nThe character in choice is a vowel." << endl; break; default: cout << "\nThe character in choice is not a vowel." << endl; break; //this break is optional } // end of switch statement

Because character data types are always converted to integers in an expression, a switch statement can also be used to "switch" on the basis of the value of a character expression