Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 SELECTION using IF and IF-ELSE Chapter 4. 2 Agenda Background  One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else.

Similar presentations


Presentation on theme: "1 SELECTION using IF and IF-ELSE Chapter 4. 2 Agenda Background  One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else."— Presentation transcript:

1 1 SELECTION using IF and IF-ELSE Chapter 4

2 2 Agenda Background  One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls

3 3 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)

4 4 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

5 5 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

6 6 Who are these gatekeepers ? There are two types of conditional statements : The if Statement The if…else Statement

7 7 Agenda Background One Way selection (if)  Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls

8 8 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!”;

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

10 10 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

11 11 One-Way Selection Flowchart (if) score==100 true false CONGRATS! Next statement

12 12 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

13 13 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 =!

14 14 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 ____________

15 15 Agenda Background One Way selection (if) Two Way selection (if-else)  Compound Statements Nested if-else Logical operators Common pitfalls

16 16 The if…else statement The if…else statement selects between one of two statements. Here is the syntax of if-else: if (condition) statement1; else statement2; So how does this work ….. ? Notice: no condition here

17 17 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

18 18 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

19 19 Conditional Flowchart (if-else) hours>40 truefalse calc pay with overtime calc pay regular display pay to screen

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

21 21 Implementing the Branch The actual C++ to do this: if (hours > 40) gross_pay = rate * 40 + 50; else gross_pay = rate * hours; Notice, one condition, for two statements Notice: no condition here! “else” means “condition was false”

22 22 Full Application: Calculating Pay // pay.cpp int main() {float hours, pay, rate; cout << "enter hours and rate: "; cin >> hours >> rate; if (hours > 40) pay = rate * 40 + 50; else pay = rate * hours; cout << "pay is " << pay; } This is Step4. Calc Result

23 23 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 ____________

24 24 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 ____________

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

26 26 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements  Nested if-else Logical operators Common pitfalls

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

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

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

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

31 31 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else  Logical operators Common pitfalls

32 32 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

33 33 Nested if-else (multi-way branch) if (expr1) { block1 } else if (expr2) { block2 } else if (expr3) {block 3} else {block4} Syntax: 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;} Example:

34 34 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 ____________

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

36 36 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

37 37 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”;

38 38 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”;

39 39 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators  Common pitfalls

40 40 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

41 41 Compound Conditions Logical AND means true only if both true AND operator: && p && q pq TTT TFF FTF FFF

42 42 Compound Conditions Logical OR means true if at least 1 is true OR operator: || p || q pq TTT TFT FTT FFF

43 43 Compound Conditions NOT operator: ! !p p TF FT

44 44 Compound Condition Example int main() { int n1, n2, n3; cout << “Enter three integers: “; cin >> n1 >> n2 >> n3; if (n1 <= n2 && n1 <= n3) cout << “Minimum is “ << n1 << endl; if (n2 <= n1 && n2 <= n3) cout << “Minimum is “ << n2 << endl; if (n3 <= n1 && n3 <= n2) cout << “Minimum is “ << n3 << endl; }

45 45 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

46 46 YOUR TURN 6. T/F ( 3 7) 7. T/F ! ( 2 > 3 ) 8. T/F (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

47 47 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 

48 48 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

49 49 Dangling Else A subtle bug possibility When you nest a single-choice if in a 2-choice if: if (cond1) if (cond2) statement1; else statement2; Q: Which if does the else belong to? A: the closest one above it

50 50 Dangling else…continued Compiler really interprets above like this: if (cond1) if (cond2) statement1; else statement2; Single choice if Two choice if No matter how you type it!

51 51 Dangling else…end A good idea to avoid confusion, put { } around both choices of two-choice if if (cond1) { if (cond2) statement1; } else {statement2; } Now it’s clear how to interpret it!

52 52 Go back home proud ! You’re a C++ programmer !

53 53 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!

54 54 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!

55 55 A3) Two-Way Selection What is output from the following: if (score = 100) cout<<“Congrats!”; else cout<<“Nice try”; Given a) score = 100 Congrats! b) score = 80 Congrats! (due to bug) Bug! Use ==

56 56 A4) 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"; } Need { }

57 57 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

58 58 YOUR TURN 6. F ( 3 7) 7. T ! ( 2 > 3 ) 8. T (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


Download ppt "1 SELECTION using IF and IF-ELSE Chapter 4. 2 Agenda Background  One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else."

Similar presentations


Ads by Google