Planning a Search Strategy PICO, Concept Boxes and Boolean Operators.
Chapter 3 Selection Statements §3.1 The Boolean Type and Operators §3.2 The if-else Statements...
-
Upload
polly-doyle -
Category
Documents
-
view
229 -
download
0
description
Transcript of Chapter 3 Selection Statements §3.1 The Boolean Type and Operators §3.2 The if-else Statements...
Chapter 3 Selection Statements
§3.1 The Boolean Type and Operators§3.2 The if-else Statements§3.3 Case Studies§3.4 Logical Operators§3.5 Switch Statements§3.6 Operator Precedence and Associativity
• Boolean (布尔) type– The data type with two possible values “true” or “false” bool lighton = true;
• Internal representation– “1” -> “true”; “0” -> “false”cout<<lighton;– Any non-zero value is treated as truebool lighton = -1;cout<<lighton;
§3.1 The Boolean Type and Operators
2
Relational Operators(关系运算符 )• Also named “Comparison” (比较 )operators• To compare two values• The result is a Boolean value
Operator Name Example Result < less than 1 < 2 true
<= less than or equal to 1 <= 2 true
> greater than 1 > 2 false
>= greater than or equal to 1 >= 2 false
== equal to 1 == 2 false
!= not equal to 1 != 2 true
3
bool lighton = (1>2);
• “?”: – the result value depends on the truth value of a Boolean
expression.– Boolean expression: expression with a Boolean value
(booleanExp) ? exp1 : exp2
y = (x > 0) ? 1 : -1;
If x>0, y is assigned to be 1;Otherwise, y is assigned to be -1;
Conditional (条件 ) Operator
4
• Statement (语句 ) is the minimal executable entity
• Three types of statements– Simple, composite, and empty statement
§3.2 The if-else Statements
5
• Sequence:顺序• Selection (branching):选择• Loop (Iteration):循环
Three control structures
6
• if• if-else• switch
Selection Statements
7
if (BooleanExpression) { statement(s);}
Simple if Statements
8
if (radius >= 0) { area = radius * radius * PI; cout << "The area for the circle of "
<< " radius " << radius << " is " << area;
}
Boolean Expression
true
Statement(s)
false (radius >= 0)
true
area = radius * radius * PI; cout << "The area for the circle of " << " radius " << radius << " is " << area;
false
(a) (b)
Note
9
Example: Even or Odd?
10
Listing 3.1 -- a program that checks whether a number is even or odd.
-- prompts the user to enter an integer (line 9) -- displays “number is even” if it is even (lines 11-12) and “number is odd” if it is odd (lines 14-15).
TestBoolean
A common mistake: Adding a semicolon at the end of an if clause.
Caution
11
This mistake is hard to find: Not a compilation error; Not a runtime error; A logic error!
if (radius >= 0); { area = radius * radius * PI; cout << "The area " << " is " << area; } (a)
Equivalent
Logic Error
if (radius >= 0) { }; { area = radius * radius * PI; cout << "The area " << " is " << area; } (b)
Empty Body
if (booleanExpression){ statement(s)-for-the-true-case;}else{ statement(s)-for-the-false-case;}
The if...else Statement
12
Boolean Expression
false true
Statement(s) for the false case Statement(s) for the true case
if (i > k) { if (j > k) cout << "i and j are greater than k";}else cout << "i is less than or equal to k";
Nested(嵌套 ) if Statements
13
Multiple Alternative if Statements
14
if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';
Equivalent
if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';
Trace if-else statement
15
if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';
Suppose score is 70.0 Exit the if statementThe condition is falseThe condition is falseThe condition is truegrade is C
The else clause matches the most recent if clause in the same block.
Dangling (垂悬 ) “else”
16
Use braces to make the matching clear!
}
{
17
Dangling elseNothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces:
int i = 1; int j = 2; int k = 3;
if (i > j) { if (i > k) cout << "A";}else cout << "B";
This statement prints B.
18
Tips
if (number % 2 == 0) even = true; else even = false;
(a)
Equivalent bool even = number % 2 == 0;
(b)
This is better
if (even == true) cout <<"It is even.";
(a)
Equivalent if (even) cout << "It is even.";
(b) This is better
• Error 1: Forgetting Necessary Braces
• Error 2: Wrong Semicolon at the if Line
Common Errors in Selection
19
if (radius >= 0) area = radius * radius * PI; cout << "The area " << " is " << area; (a) Wrong
if (radius >= 0) { area = radius * radius * PI; cout << "The area " << " is " << area; }
(b) Correct
if (radius >= 0); { area = radius * radius * PI; cout << "The area " << " is " << area; }
Equivalent
Logic Error if (radius >= 0) { }; { area = radius * radius * PI; cout << "The area " << " is " << area; }
Empty Body
• Error 3: Mistakenly Using = for ==
Common Errors in Selection
20
if (count = 1) cout << "count is 1" << endl;else cout << "count is not 1" << endl;
• The Problem of Body Mass Index (BMI)– BMI is a measure of health on weight. – The interpretation of BMI for people 16 years or
older is as follows:
§3.3 Case Studies
21
BMI Interpretation below 16 serious underweight
16-18 underweight 18-24 normal weight 24-29 overweight 29-35 seriously overweight above 35 gravely overweight
ComputeBMI
The US federal personal income tax is calculated based on the filing status and taxable income.The tax rates for 2002 are shown in Table 3.6.
Example: Computing Taxes
22
if (status == 0) { // Compute tax for single filers}else if (status == 1) { // Compute tax for married file jointly}else if (status == 2) { // Compute tax for married file separately}else if (status == 3) { // Compute tax for head of household}else { // Display wrong status}
Example: Computing Taxes, cont.
23
ComputeTax
• A program for a first grader to practice subtractions. – Randomly generates two single-digit integers number1 and
number2 with number1 >= number2,– displays a question such as “What is 9 – 2?”– The student types the answer,– The program displays a message to indicate whether the
answer is correct.
Example: A Simple Math Learning Tool
24
SubtractionQuiz
• Show the output of the following code, with the variable values on the right, respectively.
Review Questions
25
if(x>2) if(y>2){ int z = x+ y;
cout<< "z is "<< z << endl; }else
cout<<" x is "<< x << endl;
x = 2, y = 3;
x = 3, y = 2;
• Also known as “Boolean” operators• To operate on Boolean values to get a new
one
§3.4 Logical (逻辑 ) Operators
26
Operator Name! not&& and|| or
Truth Table
p1 p2 p1 && p2
false false false
false true false
true false false
true true true
Example
(3 > 2) && (5 >= 5) is true, because (3 > 2) and (5 >= 5) are both true.
(3 > 2) && (5 > 5) is false, because (5 > 5) is false.
p1 p2 p1 || p2
false false false
false true true
true false true
true true true
Example
(2 > 3) || (5 > 5) is false, because (2 > 3) and (5 > 5) are both false.
(3 > 2) || (5 > 5) is true, because (3 > 2) is true.
27
p !p
true false
false true
Example
!(1 > 2) is true, because (1 > 2) is false.
!(1 > 0) is false, because (1 > 0) is true.
• Listing 3.3
Example
28
int number;
cout << "Enter an integer: "; cin >> number;
cout<< (number % 2 == 0 && number % 3 == 0);cout<< (number % 2 == 0 || number % 3 == 0) ;cout<< ((number % 2 == 0 || number % 3 == 0) && !(number % 2 == 0 && number % 3 == 0)) ;
TestBooleanOperators
• &&: conditional or short-circuit AND operator p1 && p2– C++ first evaluates p1,– if p1 is true, then evaluates p2; – if p1 is false, it does not evaluate p2.
• ||: conditional or short-circuit OR operatorp1 || p2– C++ first evaluates p1, – if p1 is false then evaluates p2; – if p1 is true, it does not evaluate p2.
Short-Circuit (短路 )Operator
29
• A program to justify whether a given year it is a leap year.– The number is input by user
Example: Leap year
30
LeapYear
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
• A lottery game– A two-digit number by computer randomly– A two-digit number by user– If the two numbers are equal, user wins $10,000– If the two digits match, user wins $3,000– If one of the two digits matches, user wins $1,000
Example: Lottery
31
Lottery
switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default:
cout<<"Errors: invalid status";}
§3.5 Switch Statements
32
switch Statement Flow Chart
33
status is 0 Compute tax for single filers break
Compute tax for married file jointly break status is 1
Compute tax for married file separatly break status is 2
Compute tax for head of household break status is 3
Default actions default
Next Statement
switch Statement Rules
34
switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default;}
a value of integerenclosed in parentheses.
The case branch is executed when the value in the case statement matches the value of the switch-expression.
value1, ..., and valueN are different constant expressions
they cannot contain variables in the expression, such as 1 + x
switch Statement Rules
35
The default case is optionalIt can be used to perform actions when none of the specified cases matches
The order of the cases (including the default case) does not matter.
The keyword break is optionalIt should be used at the end of each
case to terminate the remainder of the switch statement.
If the break statement is not present, the next case statement will be executed.
switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default;}
36
Trace switch statement
switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; }
Suppose day is 3:
37
Trace switch statement
switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; }
Suppose day is 3:
38
Trace switch statement
switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; }
Suppose day is 3:
39
Trace switch statement
switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; }
Suppose day is 3:
40
Trace switch statement
switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; }
Suppose day is 3:
Trace switch Statement w/o “break”
41
cin>>ch;switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch;}
Next statement;
Suppose ch is 'a': ch is 'a': Execute this lineExecute this lineExecute this lineExecute next statement
Trace switch statement
42
switch (ch) { case 'a': cout << ch; break; case 'b': cout << ch; break; case 'c': cout << ch;}
Next statement;
Execute next statementSuppose ch is 'a': ch is 'a': Execute this lineExecute this line
• Get the year from user,, and display the animal.
Example: Chinese Zodiac
43
ChineseZodiac
• What’s the value of y after the following code?
Review Questions
44
x = 0;y = 1;switch (x+1){
case 0: y +=1;case 1: y +=2;default: y +=x;
}
How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?
• Precedence– The precedence that the operators are “operated”
• Associativity– The order that adjacent operators with the same
precedence are “operated”
§3.6 Operator Precedence and Associativity
45
Operator Precedencevar++, var-- , static_cast()+, - (plus and minus), ++var,--var (type) Casting ! (Not) *, /, % +, - (addition and subtraction) <, <=, >, >===, !=; && (AND)|| (OR)=, +=, -=, *=, /=, %= (Assignment
operator) 46
• Left-associative– Evaluate the “left” side first
• Right-associative– Evaluate the “right” side first
Operator Associativity
47
All binary operators except “=“
“=“
Example3 + 4 * 4 > 5 * 7 – 1
3 + 16 > 5 * 7 – 1
3 + 16 > 35 – 1
19 > 35 – 1
19 > 34
FALSE
3 + 4 * 4 || 5 * (4 + 3) – 1
3 + 16 || 5 * (4 + 3) – 1
19 || 5 * (4 + 3) – 1
TRUE
48
• Rational operators• Logical operators• if-else• switch• Operator precedence and associativity
Summary
49
1. Fill in the blanks to make the two code blocks equivalent.
2. Switch statements can always be converted equivalently to if-else ones, right? And vice versa? Why?
3. Assume that int a = 2 and double d = 1.1. Show the result of each expression below. The expressions are independent.
Homework Questions
50
if___________min=a;else if _____________min = b;else min = c;
min =a;if____________min = b;if____________min = c;
d += 1.5*3 +(++d);d -= 1.5*3 + d++;
a = (a =3) + a;a = a + (a =3);a += a + (a=3);a = 1 + 5 * 2 % a--;a = 2 + 4 * 5 % (++a + 1);