Download presentation
Presentation is loading. Please wait.
Published byBarrie Blake Modified over 9 years ago
1
Chapter 4 Logical Expressions & If-Else
2
2 Overview More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions u If-Else Statements u If Statements u Nested If Statements for Multi-way Branching u Testing a C++ Program
3
3 Boolean expressions u Boolean expressions (expressions of type bool) are constructed by using relational and logical operators 6 Relational Operators >= == != 3 Logical Operators !&&||
4
4 Relational operators u Relational operators and variables of any type are combined to form Boolean expressions : Left-side ExpressionOpRight-side Expression volume>mass/density B*B - 4.0 * A*C>0.0 abs(number)==35 initial!='Q'
5
5 Evaluating relational expressions int x = 4, y = 6; EXPRESSIONVALUE x < ytrue x + 2 < yfalse x != ytrue x + 3 >= ytrue y == xfalse y == x+2true y = x + 37 (not Boolean)
6
6 Assignment expressions u In C++, it is possible to use the assignment operator inside a larger expression The assignment sub-expression returns the value and type of the variable after assignment #include //what is the output? using namespace std; int main(){ int i=0; cout << (i = int(3.14159)) << endl; cout << i << endl; //what is the output? return 0;}
7
7 Comparing Strings u Two objects of type string (or a string object and a string literal) can be compared using the relational operators A character-by-character comparison is made using the ASCII code of each character u If all the characters are equal, then the 2 strings are equal Otherwise, the string with the first character of smaller ASCII value is the “lesser” string
8
8 string myState; string yourState; myState = “Texas”; yourState = “Maryland”; EXPRESSIONVALUE myState == yourState false myState > yourState true myState == “Texas”true myState < “texas”true Comparison Operator Examples
9
9 OperatorMeaning Associativity !, +, -NOT, unary +, unary -Right *, /, %Multiplication, Division, Modulus Left +, -Addition, SubtractionLeft <Less thanLeft <=Less than or equal toLeft >Greater thanLeft >=Greater than or equal toLeft ==, != Is equal to, Is not equal to Left &&logical ANDLeft ||logical OR Left = AssignmentRight
10
10 LOGICAL EXPRESSION MEANINGDESCRIPTION ! p NOT p ! p is false if p is true. ! p is true if p is false. p && q p AND q p && q is true if both p and q are true. It is false otherwise. p || q p OR qp || q is false if both p and q are false. It is true otherwise.
11
11 int age; bool isSenior, hasFever; float temperature; age = 20; temperature = 102.0; isSenior =(age >= 55);//isSenior is false hasFever =(temperature > 98.6); // hasFever is true EXPRESSIONVALUE isSenior && hasFever false isSenior || hasFever true !isSeniortrue !hasFeverfalse Logical Expression Examples
12
12 What is the value? int age, height; age = 25; height = 70; EXPRESSION VALUE ! (age < 10) ? ! (height > 60) ?
13
13 “Short-Circuit” Evaluation u C++ uses short circuit evaluation of logical expressions This means logical expressions are evaluated left to right and evaluation stops as soon as the final truth value can be determined
14
14 Short-Circuit Example int age, height; age = 25; height = 70; EXPRESSION (age > 50) && (height > 60) //false u Evaluation can stop now because result of && is only true when both sides are true u It is already determined that the expression will be false
15
15 What happens? int age, height; age = 25; height = 70; EXPRESSION ! (height > 60) || (age > 50) D oes this part need to be evaluated?
16
16 Write an expression for each u taxRate is over 25% and income is less than $20000 u temperature is less than or equal to 75 or humidity is less than 70% u age is over 21 and age is less than 60 u age is 21 or 22
17
17 Some Answers (taxRate >.25) && (income < 20000) (temperature <= 75) || (humidity <.70) (age > 21) && (age < 60) (age == 21) || (age == 22)
18
18 Short-Circuit Benefits u one Boolean expression can be placed first to “guard” a potentially unsafe operation in a second Boolean expression u time is saved in evaluation of complex expressions using operators || and &&
19
19 Short Circuit Example int number; bool test; float x; test = (number != 0) && (x < 1/number); is evaluated first and has value false u The entire expression will have a value of false u Due to short-circuiting the sub-expression to the right of && is not evaluated This avoids a possible division-by-zero error
20
20 WARNING about Expressions in C++ u “Boolean expression” means an expression whose value is true or false u an expression is any valid combination of operators and operands u each expression has a value u this can lead to UNEXPECTED RESULTS u construct your expressions CAREFULLY u use of parentheses is encouraged u otherwise, use the precedence chart to determine order
21
21 Comparing float (or double) Values u do not compare float values for equality, compare them for near-equality. float myNumber; float yourNumber; cin >> myNumber; cin >> yourNumber; test = (fabs(myNumber - yourNumber) < 0.00001); //NOT test = (myNumber == yourNumber);
22
22 Control Structures u Control structures alter the order in which statements in a program are executed By default, each statement is executed exactly once Statements are executed sequentially u There are 2 general types of control structures: Selection, also called branching Repetition, also called looping
23
23 C++ Control Structures u Selection if if... else switch u Repetition for loop while loop do... while loop
24
24 Control Structures use logical expressions which may include: 6 Relational Operators >= == != 3 Logical Operators !&&||
25
25 What can go wrong here? float average; float total; int howMany;. average = total/howMany;
26
26 Improved Version float average, float total; int howMany; if (howMany > 0) { average = total/howMany; cout << average; } else cout << “No prices were entered”;
27
27 If-Else Syntax if ( Expression ) StatementA else StatementB u NOTE: StatementA and StatementB each can be a single statement, a null statement, or a block.
28
28 if... else Provides Two-way Selection u between executing one of 2 clauses the if clause or the else clause TRUE FALSE if clauseelse clause expression
29
29 Use of blocks recommended if ( condition ) {//begin block //one or more statements go here }//end block else {//begin block //one or more statements go here }//end block
30
30 int carDoors, driverAge; float premium, monthlyPayment; if ((carDoors == 4)&&(driverAge > 24)) { premium = 650.00 ; cout << "LOW RISK "; } else { premium = 1200.00 ; cout << "HIGH RISK"; } monthlyPayment = premium / 12.0 + 5.00; If-Else with blocks
31
31 if ((carDoors == 4) && (driverAge > 24)) premium = 650.00; cout << "LOW RISK"; else premium = 1200.00; cout << "HIGH RISK"; monthlyPayment = premium / 12.0 + 5.00; u COMPILE ERROR OCCURS The “if clause” is the statement following the if What happens without braces?
32
32 Braces define blocks of code u Braces can only be omitted when each clause is a single statement if ( lastInitial <= 45 ) volume = 1; else volume = 2; cout << "Look it up in volume # " << volume << "of NYC phone book";
33
33 If-Then-Else for a mail order u Assign value.25 to discountRate and assign value 10.00 to shipCost if purchase is over 100.00 u Otherwise, assign value.15 to discountRate and assign value 5.00 to shipCost u Either way, calculate totalBill
34
34 These braces cannot be omitted if (purchase > 100.00) { discountRate = 0.25; shipCost = 10.00; } else { discountRate =.15; shipCost = 5.00; } totalBill = purchase *(1- discountRate) + shipCost;
35
35 If statement is a selection u of whether or not to execute a statement which can be a single statement or a block TRUE FALSE statement expression
36
36 Terminating your program int number; cout << "Enter a non-zero number"; cin >> number; if (number == 0) { cout << "Bad input. Program terminated"; return 1; } // otherwise continue processing
37
37 if (number == 0) if (! number) {.... } u Each expression is only true when number has value 0. These are equivalent. Why?
38
38 Write If or If-Else for each u If taxCode is 7, increase price by adding taxRate times price to it u If code has value 1, read values for income and taxRate from cin, and calculate and display taxDue as their product u If A is strictly between 0 and 5, set B equal to 1/A, otherwise set B equal to A
39
39 Possible Answers if (taxCode == 7) price = price + taxRate * price; if ( code == 1) { cin >> income >> taxRate; taxDue = income * taxRate; cout << taxDue; } if (( A > 0)&&(A < 5)) B = 1/A; else B = A;
40
40 What output? and Why? int age; age = 30; if ( age < 18 ) cout << “Do you drive?”; cout << “Too young to vote”;
41
41 What output? and Why? int code; code = 0; if ( ! code ) cout << “Yesterday”; else cout << “Tomorrow”;
42
42 What output? and Why? int number; number = 0; if (number = 0) cout << "Zero value"; else cout << "Non-zero value";
43
43 Chained If u The if clause & else clause of an if...else statement can contain any kind of statement including another if…else statement u This is called multi-way branching
44
44 Chained if Statements if (Expression1) Statement_1 else if (Expression2) Statement_2... else if (ExpressionN) Statement_N else Statement_N_plus_1 EXACTLY 1 of these statements will be executed.
45
45 Chained if Statements u Each Expression is evaluated in sequence, until some Expression is found that is true u Only the specific Statement following that particular true Expression is executed u If no Expression is true, the Statement following the final else is executed u The final else and final Statement are optional If omitted, when no Expression is true no Statement is executed
46
46 Multi-way Branching if (creditsEarned >= 90) cout << "SENIOR STATUS"; else if (creditsEarned >= 60) cout << "JUNIOR STATUS"; else if (creditsEarned >= 30) cout << "SOPHOMORE STATUS"; else cout << "FRESHMAN STATUS";
47
47 Writing Chained if Statements u Display one word to describe the int value of number as “Positive”, “Negative”, or “Zero” u Your city classifies a pollution index less than 35 as “Pleasant” 35 through 60 as “Unpleasant” and above 60 as “Health Hazard” u Display the correct description of the pollution index value
48
48 One Answer if (number > 0) cout << "Positive"; else if (number < 0) cout << "Negative"; else cout << "Zero";
49
49 Other Answer if ( index < 35 ) cout << “Pleasant”; else if ( index <= 60 ) cout << “Unpleasant”; else cout << “Health Hazard”;
50
50 Write a void Function… u …called DisplayMessage (which you can call from main) to describe the pollution index value it receives as an argument u Write a driver program to test this function u Your city describes a pollution index less than 35 as “Pleasant” 35 through 60 as “Unpleasant” above 60 as “Health Hazard”
51
51 void DisplayMessage(int index) { if (index < 35) cout << "Pleasant"; else if (index <= 60) cout << "Unpleasant"; else cout << "Health Hazard"; }
52
52 The Driver Program #include using namespace std; void DisplayMessage (int); //prototype int main () { int pollutionIndex; //declare variable cout << "Enter air pollution index"; cin >> pollutionIndex; DisplayMessage(pollutionIndex); //call return 0; }
53
53 Nested Decisions more u Sometimes you will need more than two parts. if/else (can get very messy— careful indenting helps) Use nested if/else statements (can get very messy— careful indenting helps) if(isHungry(Lisa) && isHungry(Ed)) { if(isHere(Boss) && isHungry(Boss)) { eat(FOOD_FANCY); shiftAppts(12.0,pm,2.0,pm); eat(FOOD_FANCY); shiftAppts(12.0,pm,2.0,pm); } else { if(isHere(Jim) && isHere(Lori)) else { if(isHere(Jim) && isHere(Lori)) { eat(FOOD_CAFETERIA); { eat(FOOD_CAFETERIA); } else { if(getTime() > MID_DAY) { eat(FOOD_BROWNBAG); else { if(getTime() > MID_DAY) { eat(FOOD_BROWNBAG); } else cancelLunch(); } } else cancelLunch(); } }}
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.