SELECTION using IF and IF-ELSE Chapter 4 1 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 2 Review: Standard Program Structure To solve most problems, your main() program will generally look like this (conceptually) 1. Declare variables for input, result and intermediate data 2. Ask for data (cout) 3. Input data (cin) 4. Calculate result 5. Output result (cout) 3 Simple Flow of Control Flow of control The order in which statements are executed Sequential The normal default flow…one line after the other Conditional (or Branch, or Selection) Lets program choose between one or more alternatives Loop (or Iteration) Lets program repeat a block of statements many times 4 Which way to go? Conditional statements allow execution of certain statements only if a particular condition is satisfied Consider these statements as some kind of a gate keeper that allows entry only if a condition is satisfied 5 Who are these gatekeepers ? There are two types of conditional statements : The if Statement The if…else Statement 6 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 7 The plain old if… The if statement allows conditional execution What does this mean ? Consider this …. You get an award only if you get a perfect score on a test if (score == 100) cout<<“Congratulations!”; 8 if statement syntax if (condition) statement ; Condition – is a logical expression like score == 100 x+y>10 ans!=‘y’ Statement – is any executable statement like cout<<“Congrats!”; OR x = x + 50; 9 How it works The if statement first evaluates the condition… for example… if (score == 100) cout<<“Congratulations!”; if score is 100 then the condition evaluates to true so it displays a Congratulations! message if score is not 100, it skips to the next line…no output 10 One-Way Selection Flowchart (if) true score==100 false CONGRATS! Next statement 11 Logical Expressions Logical expressions are expressions that are either true or false (4<3) (hours>40) (Length>=Width) relational operators such as ‘>’ (greater than) are used to compare variables and/or numbers 12 Relational Operators The Six Relational operators (No spaces allowed between the symbols!) • • • • • • < less than > greater than <= greater than or equal to >= less than or equal to == equal or equivalent (Only use on int or char) != is not equal to (Only use on int or char) (not suitable with floats due to roundoff error) Common source of errors, don’t use one =! 13 Q1) One-Way Selection What is output from following: if (score > 65) cout<<“Pass! ”; cout<<“Congrats!”; Given a) score = 80 ____________ b) score = 40 ____________ c) score = 65 ____________ 14 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 15 The if…else statement The if…else statement selects between one of two statements. Here is the syntax of if-else: if (condition) statement1; Notice: no condition here else statement2; So how does this work ….. ? 16 How it works Again, condition is a logical expression like score > 65 statement1 and statement2 are executable, like cout<<“Congrats!”; OR x = x + 50; If condition is true then statement1 will execute Otherwise (i.e. condition is false) statement2 will execute 17 if…else Example To calculate hourly wages there are two choices Regular time ( up to 40 hours) • gross_pay = rate * hours; Overtime ( over 40 hours) gets $50 bonus • gross_pay = rate * 40 + 50; The program must choose which of these expressions to use 18 Conditional Flowchart (if-else) false true hours>40 calc pay with overtime calc pay regular display pay to screen 19 Designing the Conditional Determine if (hours >40) is true If it is true, then use gross_pay = rate * 40 + 50; If it is not true, then use gross_pay = rate * hours; 20 Implementing the Branch The actual C++ to do this: if (hours > 40) gross_pay = rate * 40 + 50; Notice: no condition here! else “else” means gross_pay = rate * hours; “condition was false” Notice, one condition, for two statements 21 Full Application: Calculating Pay // pay.cpp int main() { float hours, pay, rate; cout << "enter hours and cin >> hours >> rate; rate: "; This is Step4. Calc Result if (hours > 40) pay = rate * 40 + 50; else pay = rate * hours; cout << "pay is " << pay; } 22 Q2) Two-Way Selection What is output from the following: if (score > 60) cout<<“Pass--”; else cout<<“Fail--”; cout<<“Have a nice day!”; Given a) score = 80 ____________ b) score = 40 ____________ c) score = 60 ____________ 23 Q3) Two-Way Selection What is output from the following: if (score = 100) cout<<“Congrats!”; else cout<<“Nice try”; Given a) score = 100 ____________ b) score = 80 ____________ 24 Application of 2-Way Selection //cost.cpp see p67-68 Use for Problem 10 int number, cost; cout << "Number purchased: "; cin >> number; if (number < 5) cost = 12 * number; else cost = 10 * number; cout << number << " baseballs cost $" << cost; 25 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 26 Compound Statements A compound statement is more than one statement enclosed in { } Branches of if or if-else statements often need to execute more that one statement Example: if (condition) { statements for true } else { statements for false } 27 Example with two if-else statements if (hours > 40.0) pay = 40.0 * rate + 50; else pay = hours * rate; cout << "pay is " << pay; if (hours > 40.0) cout << " overtime worked"; else cout << " no overtime worked"; 28 Above redone (simplified) with compound statements if (hours > 40.0) { pay = 40.0 * rate + 50; cout << " pay is " << pay << " overtime worked"; } else { pay = hours * rate; cout << " pay is " << pay << " no overtime"; } 29 Q4) What’s wrong with this code? if (hours > 40.0) pay = 40.0 * rate + 50; cout << " pay is " << pay << " overtime worked"; else { pay = hours * rate; cout << " pay is " << pay << " no overtime"; } 30 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 31 Nesting and Multi-Way Branches How to select from more than two possibilities? How to check a variable is inside a range of values? Answer: put an if-else inside if or else block …nesting if (expr1) statement1; // do if expr1 is true else // do if expr1 is false if (expr2) statement2; // expr1 false, expr2 true else statement3; // both expr1 and expr2 false 32 Nested if-else (multi-way branch) Syntax: if (expr1) { block1 } else if (expr2) { block2 } else if (expr3) {block 3} else {block4} Example: if( grade>=90) cout<<"Your GPA is A."<<endl; else if (grade>=80) cout<<"Your GPA is B."<<endl; else if (grade>=70) cout<<"Your GPA is C."<<endl; else if (grade>=60) cout<<"Your GPA is D."<<endl; else {cout<<"Your GPA is F."<<endl; cout<<"You will cry!"<<endl;} 33 Q5) What does this code produce: if( grade>=90) cout<<"GPA is A."<<endl; else if (grade>=70) cout<<"GPA is C."<<endl; else if (grade>=80) cout<<"GPA is B."<<endl; Given a) grade = 93 ____________ b) grade = 85 ____________ c) grade = 75 ____________ d) grade = 45 ____________ 34 Application – Multiway Branch // suit.cpp See p75 Use for Problem 11 char suit; // 'C', 'D', 'H', or 'S' cout << "First letter of suit (C,D,H, or S): "; cin >> suit; if (suit == 'C') cout << "clubs"; else if (suit == 'D') cout << "diamonds"; else if (suit == 'H') cout << "hearts"; else if (suit == 'S') cout << "spades"; else cout << "Invalid suit"; 35 Time for Break! Download Lab3If.cpp Work on 1-6, 11 You need to do 1 thru 10 for 10 points Call me over if you need help 36 Application: How to tell if n is in the correct range cout<<“Enter a number between 1 and 10”; cin>>n; if (n>=1) if (n<=10) cout<<“OK, n is between 1 and 10!”; else cout<<“n is too big”; else cout<<“n is too small”; 37 A better way using && cout<<“Enter a number between 1 and 10”; cin>>n; if (n>=1 && n <=10) cout<<“OK, n is between 1 and 10!”; else cout<<“illegal value of n”; 38 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 39 Logical Operators AND operator: p && q OR operator: p || q NOT operator: !p Both p and q are relational expressions (like a<5) or boolean (true/false) expressions 40 Compound Conditions Logical AND means true only if both true AND operator: && p && q p q p && q T T F F T F T F T F F F 41 Compound Conditions Logical OR means true if at least 1 is true OR operator: || p || q p q p || q T T F F T F T F T T T F 42 Compound Conditions NOT operator: ! !p p !p T F F T 43 Compound Condition Example int main() { int n1, n2, n3; cout << “Enter three integers: cin >> n1 >> n2 >> n3; if (n1 <= n2 && n1 <= n3) cout “ << n1 << endl; if (n2 <= n1 && n2 <= n3) cout “ << n2 << endl; if (n3 <= n1 && n3 <= n2) cout “ << n3 << endl; } “; << “Minimum is << “Minimum is << “Minimum is 44 OR Example 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”; } This will accept both ‘Y’ and ‘y’ as an answer 45 YOUR TURN 6. T/F 7. T/F 8. T/F ( 3 < 2 ) && (5 > 7) !(2>3) (25 = = 25 ) || ( 2 > 3 ) 9. the expression: ( number > 10 && number < 40 ) is TRUE, when a) number is larger than 40 b) number is smaller than 10 c) number is between 10 and 40 d) Never 46 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 47 Common Pitfalls in Selection/Logic Dangling else Using = instead of == Forgetting { } around multiple statement blocks Not testing your proposed solution using simple test data values Trying to solve all at once…a mess! Better: build up solution step by step: see p79-82 Read/steal code examples from text noted on handout If stuck, start small, do drill exercises, then tackle programs 48 Dangling Else A subtle bug possibility When you nest a single-choice if in a 2-choice if: if (cond1) if (cond2) Q: Which if does statement1; the else belong to? else statement2; A: the closest one above it 49 Dangling else…continued Compiler really interprets above like this: if (cond1) Single choice if if (cond2) Two choice if statement1; else statement2; No matter how you type it! 50 Dangling else…end A good idea to avoid confusion, put { } around both choices of two-choice if if (cond1) { if (cond2) statement1; Now it’s clear how } to interpret it! else { statement2; } 51 Go back home proud ! You’re a C++ programmer ! 52 A1) One-Way Selection What is output from following: if (score > 65) cout<<“Pass! ”; cout<<“Congrats!”; Given a) score = 80 Pass! Congrats! b) score = 40 Congrats! c) score = 65 Congrats! 53 A2) Two-Way Selection What is output from the following: if (score > 60) cout<<“Pass--”; else cout<<“Fail--”; cout<<“Have a nice day!”; Given a) score = 80 Pass--Have a nice day! b) score = 40 Fail--Have a nice day! c) score = 60 Fail--Have a nice day! 54 A3) Two-Way Selection What is output from the following: if (score = 100) cout<<“Congrats!”; else cout<<“Nice try”; Bug! Use == Given a) score = 100 b) score = 80 Congrats! Congrats! (due to bug) 55 A4) What’s wrong with this code? if (hours > 40.0) pay = 40.0 * rate + 50; cout << " pay is " << pay << " overtime worked"; else { Need { } pay = hours * rate; cout << " pay is " << pay << " no overtime"; } 56 A5) What does this code produce: if( grade>=90) cout<<"GPA is A."<<endl; else if (grade>=70) cout<<"GPA is C."<<endl; else if (grade>=80) cout<<"GPA is B."<<endl; Given a) grade = 93 A b) grade = 85 C c) grade = 75 C d) grade = 45 nothing 57 YOUR TURN 6. F 7. T 8. T ( 3 < 2 ) && (5 > 7) !(2>3) (25 = = 25 ) || ( 2 > 3 ) 9. the expression: ( number > 10 && number < 40 ) is TRUE, when a) number is larger than 40 b) number is smaller than 10 c) number is between 10 and 40 d) Never 58