Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 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 true bool lighton = -1; cout<<lighton; §3.1 The Boolean Type and Operators 2

3 Relational Operators( 关系运算符 ) Also named “Comparison” ( 比较 )operators To compare two values The result is a Boolean value 3 bool lighton = (1>2);

4 “ ? ” : – 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

5 Statement ( 语句 ) is the minimal executable entity Three types of statements – Simple, composite, and empty statement §3.2 The if-else Statements 5

6 Sequence :顺序 Selection (branching) :选择 Loop (Iteration) :循环 Three control structures 6

7 if if-else switch Selection Statements 7

8 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; }

9 Note 9

10 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

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

12 if (booleanExpression){ statement(s)-for-the-true-case; } else{ statement(s)-for-the-false-case; } The if...else Statement 12

13 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

14 Multiple Alternative if Statements 14

15 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 false The condition is truegrade is C

16 The else clause matches the most recent if clause in the same block. Dangling ( 垂悬 ) “ else ” 16 Use braces to make the matching clear! } {

17 17 Dangling else Nothing 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 18 Tips

19 Error 1: Forgetting Necessary Braces Error 2: Wrong Semicolon at the if Line Common Errors in Selection 19

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

21 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 ComputeBMI

22 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

23 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

24 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

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

26 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

27 Truth Table 27

28 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

29 &&: 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 operator p1 || 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

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

31 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

32 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

33 switch Statement Flow Chart 33

34 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 integer enclosed 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

35 switch Statement Rules 35 The default case is optional It 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 optional It 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 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 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 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 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 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:

41 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 line Execute next statement

42 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 line

43 Get the year from user,, and display the animal. Example: Chinese Zodiac 43 ChineseZodiac

44 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; }

45 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

46 Operator Precedence var++, var--, static_cast() +, - (plus and minus), ++var,--var (type) Casting ! (Not) *, /, % +, - (addition and subtraction), >= ==, !=; && (AND) || (OR) =, +=, -=, *=, /=, %= (Assignment operator) 46

47 Left-associative – Evaluate the “left” side first Right-associative – Evaluate the “right” side first Operator Associativity 47 All binary operators except “=“ “=“

48 Example 3 + 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

49 Rational operators Logical operators if-else switch Operator precedence and associativity Summary 49

50 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);


Download ppt "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."

Similar presentations


Ads by Google