1 SELECTION using IF and IF-ELSE Chapter 4. 2 Agenda Background One Way selection (if) Two Way...
-
Upload
dustin-moore -
Category
Documents
-
view
257 -
download
5
Transcript of 1 SELECTION using IF and IF-ELSE Chapter 4. 2 Agenda Background One Way selection (if) Two Way...
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
Logical operators
Common pitfalls
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 result5. Output result (cout)
4
Simple Flow of ControlFlow of control
The order in which statements are executed
SequentialThe 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
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
Who are these gatekeepers ?
There are two types of conditional
statements :
The if Statement
The if…else Statement
7
Agenda
Background
One Way selection (if) Two Way selection (if-else)
Compound Statements
Nested if-else
Logical operators
Common pitfalls
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
if statement syntaxif (condition) statement ;
Condition – is a logical expression likescore == 100 x+y>10 ans!=‘y’
Statement – is any executable statement like
cout<<“Congrats!”; OR x = x + 50;
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
One-Way Selection Flowchart (if)
score==100
true
false CONGRATS!
Next statement
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
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
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
Agenda
Background
One Way selection (if)
Two Way selection (if-else)
Compound Statements
Nested if-else
Logical operators
Common pitfalls
16
The if…else statementThe 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
How it worksAgain, 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
if…else Example
To calculate hourly wages there are two choicesRegular 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
Conditional Flowchart (if-else)
hours>40truefalse
calc paywith overtime
calc payregular
display payto screen
20
Designing the Conditional
Determine if (hours >40) is trueIf it is true, then use gross_pay = rate * 40 + 50;
If it is not true, then use gross_pay = rate * hours;
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
Full Application: Calculating Pay// pay.cppint 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
Q2) Two-Way SelectionWhat 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
Q3) Two-Way SelectionWhat is output from the following:
if (score = 100)
cout<<“Congrats!”;
else
cout<<“Nice try”;
Given a) score = 100 ____________
b) score = 80 ____________
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
Agenda
Background
One Way selection (if)
Two Way selection (if-else)
Compound Statements Nested if-else
Logical operators
Common pitfalls
27
Compound StatementsA compound statement is more than one statement enclosed in { } Branches of if or if-else statements often need to execute more that one statementExample: if (condition) { statements for true } else {
statements for false }
28
Example with two if-else statements
if (hours > 40.0)pay = 40.0 * rate + 50;
elsepay = hours * rate;
cout << "pay is " << pay;
if (hours > 40.0)cout << " overtime worked";
elsecout << " no overtime worked";
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
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
Agenda
Background
One Way selection (if)
Two Way selection (if-else)
Compound Statements
Nested if-else Logical operators
Common pitfalls
32
Nesting and Multi-Way BranchesHow 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 …nestingif (expr1) statement1; // do if expr1 is trueelse // do if expr1 is false
if (expr2) statement2; // expr1 false, expr2 true
elsestatement3; // both expr1 and expr2 false
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
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
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
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
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!”;
elsecout<<“n is too big”;
elsecout<<“n is too small”;
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
Agenda
Background
One Way selection (if)
Two Way selection (if-else)
Compound Statements
Nested if-else
Logical operators Common pitfalls
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
Compound Conditions
Logical AND means true only if both true
AND operator: && p && q
p q p && q
T T T
T F F
F T F
F F F
42
Compound Conditions
Logical OR means true if at least 1 is true
OR operator: ||p || q
p q p || q
T T T
T F T
F T T
F F F
43
Compound Conditions
NOT operator: ! !p
p !p
T F
F T
44
Compound Condition Exampleint 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
OR Exampleint 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
YOUR TURN6. T/F ( 3 < 2 ) && (5 > 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
Agenda
Background
One Way selection (if)
Two Way selection (if-else)
Compound Statements
Nested if-else
Logical operators
Common pitfalls
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
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
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
Dangling else…endA 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
Go back home proud ! You’re a C++ programmer !
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
A2) Two-Way SelectionWhat 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
A3) Two-Way SelectionWhat 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
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
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
YOUR TURN6. F ( 3 < 2 ) && (5 > 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