Selection Structures if and switch Statements Selection Statements

  • Slides: 55
Download presentation
Selection Structures: if and switch Statements

Selection Structures: if and switch Statements

Selection Statements – In this chapter we study statements that allow alternatives to straight

Selection Statements – In this chapter we study statements that allow alternatives to straight sequential processing. In particular: • if statements (do this only if a condition is true) • if-else statements (do either this or that) • Logical expressions (evaluate to true or false) • Boolean operators (not: ! and: && or: ||) 2

4. 1 Control Structures – Programs must often anticipate a variety of situations. –

4. 1 Control Structures – Programs must often anticipate a variety of situations. – Consider an Automated Teller Machine: • ATMs must serve valid bank customers. They must also reject invalid PINs. • The code that controls an ATM must permit these different requests. • Software developers must implement code that anticipates all possible transactions. 3

4. 2 Logical Expressions 4

4. 2 Logical Expressions 4

Boolean Variables t t bool variable Included with C++ compiler bool leap. Year =

Boolean Variables t t bool variable Included with C++ compiler bool leap. Year = true; leap. Year = false; leap. Year; // Non zero return value // Zero return value 5

Boolean Expressions Examples (Write T for True, or F for False): int n 1

Boolean Expressions Examples (Write T for True, or F for False): int n 1 = 55; int n 2 = 75; n 1 < n 2 // _____ n 1 > n 2 // _____ (n 1 + 35) > n 2 // _____ (n 1 -n 2) < 0. 1 // _____ n 1 == n 2 // _____ 6

Logical Expressions – Logical expressions often use these relational operators: 7

Logical Expressions – Logical expressions often use these relational operators: 7

Logical Operators t Logical operator (&& means AND) used in an if. . .

Logical Operators t Logical operator (&& means AND) used in an if. . . else statement: ( (try. It >= 0) && (try. It <= 100) ) t Logical operator (| | means OR) used in an if. . . else statement: ( (try. It >= 0) | | (try. It <= 100) ) 8

Using && Assume try. It = 90, t Is try. It within the range

Using && Assume try. It = 90, t Is try. It within the range of 0 and 100 ? t ( (try. It >= 0) && (try. It <= 100) ) ( ( 90 >= 0) && ( 90 <= 100) ) ( 1 && 1 ) 1 9

Using && Assume try. It = 99 t Is try. It outside the range

Using && Assume try. It = 99 t Is try. It outside the range of 0 and 100 ? t ( (try. It < 0) ¦¦ (try. It > 100) ) ( ( 99 < 0) ¦¦ ( 99 > 100) ) ( 0 ¦¦ 0 ) 0 10

Truth Tables for Boolean Operators t Truth tables Logical operators !, ¦¦, && –

Truth Tables for Boolean Operators t Truth tables Logical operators !, ¦¦, && – 1 is a symbol for true – 0 is a symbol for false 11

Precedence of Operators t t Precedence: most operators are evaluated (grouped) in a left-to-right

Precedence of Operators t t Precedence: most operators are evaluated (grouped) in a left-to-right order: – a / b / c / d is equivalent to (((a/b)/c)/d) Assignment operators group in a right-toleft order so the expression – x = y = z = 0. 0 is equivalent to (x=(y=(z=0. 0))) 12

Precedence of Operators 13

Precedence of Operators 13

Boolean Assignment bool same; same = true; Form: variable = expression; Example: same =

Boolean Assignment bool same; same = true; Form: variable = expression; Example: same = (x = = y); 14

4. 3 Introduction to the if Dependent Control Statement – The if is the

4. 3 Introduction to the if Dependent Control Statement – The if is the first statement that alters strict sequential control. – General form if ( logical-expression ) true-part ; • logical-expression: any expression that evaluates to nonzero (true) or zero (false). • In C++, almost everything is true or false. 15

if Control Statements with Two Alternatives – The logical expression is evaluated. When true,

if Control Statements with Two Alternatives – The logical expression is evaluated. When true, the true -part is executed and the false-part is disregarded. When the logical expression is false, the false-part executes. – General Form if ( logical-expression ) true-part ; else false-part ; 16

What happens when an if statement executes? gross >100. 0 True net=gross-tax False net=gross

What happens when an if statement executes? gross >100. 0 True net=gross-tax False net=gross • After the logical expression of the if statement evaluates, the true-part executes only if the logical expression was true. 17

Programming Tip t t Using = for == is a common mistake. For example

Programming Tip t t Using = for == is a common mistake. For example the following statements are legal: int x = 25; Because assignment statements evaluate to the expression on the right of =, x = 1 is always 1, which is nonzero, which is true: if (x = 1) // should be (x == 1) 18

4. 4 if Statements with Compound Alternatives – General form (also known as a

4. 4 if Statements with Compound Alternatives – General form (also known as a block): { statement-1 ; statement-2 ; . . . statement-N ; } – The compound statement groups together many statements that are treated as one. 19

Writing Compound Statements if (transaction. Type == 'c') { // process check cout <<

Writing Compound Statements if (transaction. Type == 'c') { // process check cout << "Check for $" << transaction. Amount << endl; balance = balance transaction. Amount; } else { // process deposit cout << "Deposit of $" << transaction. Amount << endl; balance = balance + 20

4. 5 Decision Steps in Algorithms t t Algorithm steps that select from a

4. 5 Decision Steps in Algorithms t t Algorithm steps that select from a choice of actions are called decision steps. The algorithm in the following case contains decisions steps to compute an employee’s gross and net pay after deductions. The decision steps are coded as if statements. Payroll Case Study 21

Decision Steps in Algorithms t Statement: Your company pays its hourly workers once a

Decision Steps in Algorithms t Statement: Your company pays its hourly workers once a week. An employee’s pay is based upon the number of hours worked (to the nearest half hour) and the employee’s hourly pay rate. Weekly hours exceeding 40 are paid at a rate of time and a half. Employees who earn over $100 a week must pay union dues of $15 per week. Write a payroll program that will determine the gross pay and net pay for an employee. 22

Decision Steps in Algorithms t Analysis: The problem data include the input data for

Decision Steps in Algorithms t Analysis: The problem data include the input data for hours worked and hourly pay and two required outputs, gross pay and net pay. There also several constants: the union dues ($15), the minimum weekly earnings before dues must be paid ($100), the maximum hours before overtime must be paid (40), and the overtime rate (1. 5 times the usual hourly rate). With this information, we can begin to write the data requirements for this problem. We can model all data using the money (see Section 3. 7) and float data types. 23

Decision Steps in Algorithms t Program Design: The problem solution requires that the program

Decision Steps in Algorithms t Program Design: The problem solution requires that the program read the hours worked and the hourly rate before performing any computations. After reading these data, we need to compute and then display the gross pay and net pay. The structure chart for this problem (Figure 4. 6) shows the decomposition of the original problem into five subproblems. We will write three of the subproblems as functions. For these three subproblems, the corresponding function name appears under its box in the structure chart. 24

Decision Steps in Algorithms – Display user instructions (function instruct. User). – Enter hours

Decision Steps in Algorithms – Display user instructions (function instruct. User). – Enter hours worked and hourly rate. – Compute gross pay (function compute. Gross). – Compute net pay (function compute. Net). – Display gross pay and net pay. 25

Payroll. Functions. cpp // // // File: payroll. Functions. cpp Computes and displays gross

Payroll. Functions. cpp // // // File: payroll. Functions. cpp Computes and displays gross pay and net pay given an hourly rate and number of hours worked. Deducts union dues of $15 if gross salary exceeds $100; otherwise, deducts no dues. #include <iostream> #include "my. Money. h" 26

Payroll. Functions. cpp using namespace std; // Functions used. . . void instruct. User();

Payroll. Functions. cpp using namespace std; // Functions used. . . void instruct. User(); money compute. Gross(float, money); money compute. Net(money); const money MAX_NO_DUES = 100. 00; const money dues = 15. 00; const float MAX_NO_OVERTIME = 40. 0; const float OVERTIME_RATE = 1. 5; 27

Payroll. Functions. cpp int main { float money () hours; rate; gross; net; //

Payroll. Functions. cpp int main { float money () hours; rate; gross; net; // Display user instructions. instruct. User(); 28

Payroll. Functions. cpp // Enter hours and rate. cout << "Hours worked: "; cin

Payroll. Functions. cpp // Enter hours and rate. cout << "Hours worked: "; cin >> hours; cout << "Hourly rate: "; cin >> rate; // Compute gross salary. gross = compute. Gross(hours, rate); // Compute net salary. net = compute. Net(gross); 29

Payroll. Functions. cpp // Print gross and net. cout << "Gross salary is "

Payroll. Functions. cpp // Print gross and net. cout << "Gross salary is " << gross << endl; cout << "Net salary is " << net << endl; return 0; } 30

Payroll. Functions. cpp // Displays user instructions void instruct. User() { cout << "This

Payroll. Functions. cpp // Displays user instructions void instruct. User() { cout << "This program computes gross and net salary. " << endl; cout << "A dues amount of " << dues << " is deducted for" << endl; cout << "an employee who earns more than " << MAX_NO_DUES << endl; cout << "Overtime is paid at the rate of " << OVERTIME_RATE << endl; 31

Payroll. Functions. cpp cout << "times the regular rate for hours worked over "

Payroll. Functions. cpp cout << "times the regular rate for hours worked over " << MAX_NO_OVERTIME << endl; cout << "Enter hours worked and hourly rate" << endl; cout << "on separate lines after the prompts. " << endl; cout << "Press <return> after typing each number. " << endl; } // end instruct. User 32

Payroll. Functions. cpp // FIND THE GROSS PAY money compute. Gross (float hours, {

Payroll. Functions. cpp // FIND THE GROSS PAY money compute. Gross (float hours, { // Local data. . . money gross; money regular. Pay; money overtime. Pay; money rate) // Compute gross pay. if (hours > MAX_NO_OVERTIME) { regular. Pay = MAX_NO_OVERTIME * rate; 33

Payroll. Functions. cpp overtime. Pay = (hours - MAX_NO_OVERTIME) * OVERTIME_RATE * rate; gross

Payroll. Functions. cpp overtime. Pay = (hours - MAX_NO_OVERTIME) * OVERTIME_RATE * rate; gross = regular. Pay + overtime. Pay; } else gross = hours * rate; } return gross; // end compute. Gross 34

Payroll. Functions. cpp // Find the net pay money compute. Net (money gross) {

Payroll. Functions. cpp // Find the net pay money compute. Net (money gross) { money net; // Compute net pay. if (gross > MAX_NO_DUES) net = gross - dues; else net = gross; } return net; // end compute. Net 35

Payroll. cpp Program output This program computes gross and net salary. A dues amount

Payroll. cpp Program output This program computes gross and net salary. A dues amount of $15. 00 is deducted for an employee who earns more than $100. 00 Overtime is paid at the rate of 1. 5 times the regular rate on hours worked over 40 Enter hours worked and hourly rate on separate lines after the prompts. Press <return> after typing each number. 36

Payroll. cpp Program output Hours worked: 50 Hourly rate: 6 Gross salary is $330.

Payroll. cpp Program output Hours worked: 50 Hourly rate: 6 Gross salary is $330. 00 Net salary is $315. 00 37

4. 6 Checking the Correctness of an Algorithm t t Verifying the correctness of

4. 6 Checking the Correctness of an Algorithm t t Verifying the correctness of an algorithm is a critical step in algorithm design and often saves hours of coding and testing time. We will now trace the execution of the refined algorithm for the payroll problem solved in the last section. 38

Checking the Correctness of an Algorithm 1. Display user instructions. 2. Enter hours worked

Checking the Correctness of an Algorithm 1. Display user instructions. 2. Enter hours worked and hourly rate. 3. Compute gross pay. 3. 1. If the hours worked exceed 40. 0 (max hours before overtime) 3. 1. 1. Compute regular. Pay. 3. 1. 2. Compute overtime. Pay. 3. 1. 3. Add regular. Pay to overtime. Pay to get gross. else 39

Checking the Correctness of an Algorithm 3. 1. 4. Compute gross as hours *

Checking the Correctness of an Algorithm 3. 1. 4. Compute gross as hours * rate. 4. Compute net pay. 4. 1. If gross is larger than $100. 00 4. 1. 1. Deduct the dues of $15. 00 from gross pay. else 4. 1. 2. Deduct no dues. 5. Display gross and net pay. 40

4. 7 Nested if Statements and Multiple Alternative Decisions – Nested logic is one

4. 7 Nested if Statements and Multiple Alternative Decisions – Nested logic is one control structure containing another similar control structure. – An if. . . else inside another if. . . else. e. g. (the 2 nd if is placed on the same line as the 1 st): 41

Example of nested logic if(x > 0) num. Pos = num. Pos + 1;

Example of nested logic if(x > 0) num. Pos = num. Pos + 1; else if(x < 0) num. Neg = Num. Neg + 1; else num. Zero = num. Zero + 1; 42

Example of nested logic X num. Pos num. Neg num. Zero 3. 0 _______

Example of nested logic X num. Pos num. Neg num. Zero 3. 0 _______ -3. 6 _______ 4. 0 _______ Assume all variables initialized to 0 43

Writing a Nested if as a Multiple-Alternative Decision t Nested if statements can become

Writing a Nested if as a Multiple-Alternative Decision t Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult to determine the logical structure of the if statement. 44

Function display. Grade void display. Grade ( int score) { if (score >= 90)

Function display. Grade void display. Grade ( int score) { if (score >= 90) cout << "Grade is A " << endl; else if (score >= 80) cout << "Grade is B " << endl; else if (score >= 70) cout << "Grade is C " << endl; else if (score >= 60) cout << "Grade is D " << endl; else cout << "Grade is F " << endl; } 45

Order of Conditions if (score >= 60) cout << "Grade is D " <<

Order of Conditions if (score >= 60) cout << "Grade is D " << endl; else if (score >= 70) cout << "Grade is C " << endl; else if (score >= 80) cout << "Grade is B " << endl; else if (score >= 90) cout << "Grade is A " << endl; else cout << "Grade is F " << endl; 46

Short Circuit Evaluation (single == ‘y’ && gender == ‘m’ && age >= 18)

Short Circuit Evaluation (single == ‘y’ && gender == ‘m’ && age >= 18) – If single is false, gender and age are not evaluated (single == ‘y’ || gender == ‘m’ || age >= 18) – If single is true, gender and age are not evaluated 47

4. 8 The switch Control Statement switch ( switch-expression ) { case value-1 :

4. 8 The switch Control Statement switch ( switch-expression ) { case value-1 : statement(s)-1 break ; . . . // many cases are allowed case value-n : statement(s)-n break ; default : default-statement(s) } 48

Switch Control – When a switch statement is encountered, the switch-expression is evaluated. This

Switch Control – When a switch statement is encountered, the switch-expression is evaluated. This value is compared to each case value until switch-expression == case value. All statements after the colon : are executed – It is important to include the break statement 49

Example switch Statement: switch(watts) // Assume char option = '? ’ { case 25:

Example switch Statement: switch(watts) // Assume char option = '? ’ { case 25: cout << " Life expectancy is 2500 hours. " << endl; break; case 40: case 60: cout << " Life expectancy is 1000 hours. " << endl; break; 50

Example switch Statement case 75: case 100: cout << " Life expectancy is 750

Example switch Statement case 75: case 100: cout << " Life expectancy is 750 hours. " << endl; break; default: cout << "Invalid Bulb !!" << endl; } // end switch 51

Trace the previous switch – Show output when • watts = '? ' ______?

Trace the previous switch – Show output when • watts = '? ' ______? • watts = ’ 40’ ______? • watts = ’ 10' ______? • watts = ’ 200' ______? • watts = ’ 100' ______? 52

4. 9 Common Programming Errors t Failing to use { and } if(Grade >=

4. 9 Common Programming Errors t Failing to use { and } if(Grade >= 3. 5) // The true-part is the first cout only cout <<"You receive an A !!!"; cout <<"You made it by " << (Grade-3. 5) << " points"; else <<<< Error >>>> 53

Common Programming Errors t There are no compile time errors next, but there is

Common Programming Errors t There are no compile time errors next, but there is an intent error. else cout << "Sorry, you missed an A. "; cout << "You missed it by " << 3. 5 -Grade << " points"; t With the above false part, you could get this confusing output (when Grade = 3. 9): You received an A !!!. You made it by 0. 4 points. You missed it by -0. 4 points 54

Corrected Version: if(Grade >= 3. 5) { cout << "You received an A !!!

Corrected Version: if(Grade >= 3. 5) { cout << "You received an A !!! " << endl; cout << "You made it by " << (Grade-3. 5) << " points"; // Do other things if desired } else { cout << " You did NOT receive an A !!! "; cout << "You missed it by " << (3. 5 -Grade) <<" points"; } 55