Chapter 4 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Logic & program control part 2: Simple selection structures.
Logic & program control part 3: Compound selection structures.
Chapter 4: Making Decisions.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
1 Chapter 5 Branching and Method Algorithm Design.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Flow of Control is Sequential unless a “control structure” is used to change that there are 2 general types of control structures: Selection (also called.
Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What.
Multi-alternative Selection Both the if clause and the else clause of an if...else statement can contain any kind of statement, including another selection.
Conditions, logical expressions, and selection Introduction to control structures.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
1 Chapter 4 Selection and Encapsulation. 2 Chapter 4 Topics l Java Control Structures l boolean Data Type l Using Relational and Logical Operators in.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems/Headington.
Functions Modules in C++ are called functions and classes
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Control Structures I (Selection)
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Conditions, Logical Expressions, and Selection Control Structures Sumber dari :
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions, logical expressions, and selection Introduction to control structures.
Flow of Control There are 5 general types of Java control structures: Sequence (by default) Selection (also called branch or decision) Loop (also called.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 3 More Flow Of Control.
Lecture no 3 Control statements.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
COSC175-Selection1 Decisions Given hours worked and pay rate, calculate total pay What if you work overtime? How do you indicate if your work overtime?
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions, Logical Expressions, and Selection Control Structures.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
C++ Programming Control Structures I (Selection).
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 5 Topics Data Type bool
The Ohio State University
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Decisions Given hours worked and pay rate, calculate total pay
Chapter 4: Making Decisions.
Decisions Given hours worked and pay rate, calculate total pay
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Chapter 4: Control Structures I (Selection)
Topics Data Type bool Using Relational and Logical Operators to Construct and Evaluate Logical Expressions If-Then-Else Statements If-Then Statements Nested.
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
Presentation transcript:

Chapter 4 Logical Expressions & If-Else

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 Boolean expressions u Boolean expressions (expressions of type bool) are constructed by using relational and logical operators 6 Relational Operators >= == != 3 Logical Operators !&&||

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 * A*C>0.0 abs(number)==35 initial!='Q'

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 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( )) << endl; cout << i << endl; //what is the output? return 0;}

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 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 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 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 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 What is the value? int age, height; age = 25; height = 70; EXPRESSION VALUE ! (age < 10) ? ! (height > 60) ?

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 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 What happens? int age, height; age = 25; height = 70; EXPRESSION ! (height > 60) || (age > 50) D oes this part need to be evaluated?

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 Some Answers (taxRate >.25) && (income < 20000) (temperature <= 75) || (humidity <.70) (age > 21) && (age < 60) (age == 21) || (age == 22)

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 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 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 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) < ); //NOT test = (myNumber == yourNumber);

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 C++ Control Structures u Selection if if... else switch u Repetition for loop while loop do... while loop

24 Control Structures use logical expressions which may include: 6 Relational Operators >= == != 3 Logical Operators !&&||

25 What can go wrong here? float average; float total; int howMany;. average = total/howMany;

26 Improved Version float average, float total; int howMany; if (howMany > 0) { average = total/howMany; cout << average; } else cout << “No prices were entered”;

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 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 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 int carDoors, driverAge; float premium, monthlyPayment; if ((carDoors == 4)&&(driverAge > 24)) { premium = ; cout << "LOW RISK "; } else { premium = ; cout << "HIGH RISK"; } monthlyPayment = premium / ; If-Else with blocks

31 if ((carDoors == 4) && (driverAge > 24)) premium = ; cout << "LOW RISK"; else premium = ; cout << "HIGH RISK"; monthlyPayment = premium / ; u COMPILE ERROR OCCURS  The “if clause” is the statement following the if What happens without braces?

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 If-Then-Else for a mail order u Assign value.25 to discountRate and assign value to shipCost if purchase is over u Otherwise, assign value.15 to discountRate and assign value 5.00 to shipCost u Either way, calculate totalBill

34 These braces cannot be omitted if (purchase > ) { discountRate = 0.25; shipCost = 10.00; } else { discountRate =.15; shipCost = 5.00; } totalBill = purchase *(1- discountRate) + shipCost;

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 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 if (number == 0) if (! number) {.... } u Each expression is only true when number has value 0. These are equivalent. Why?

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 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 What output? and Why? int age; age = 30; if ( age < 18 ) cout << “Do you drive?”; cout << “Too young to vote”;

41 What output? and Why? int code; code = 0; if ( ! code ) cout << “Yesterday”; else cout << “Tomorrow”;

42 What output? and Why? int number; number = 0; if (number = 0) cout << "Zero value"; else cout << "Non-zero value";

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 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 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 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 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 One Answer if (number > 0) cout << "Positive"; else if (number < 0) cout << "Negative"; else cout << "Zero";

49 Other Answer if ( index < 35 ) cout << “Pleasant”; else if ( index <= 60 ) cout << “Unpleasant”; else cout << “Health Hazard”;

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 void DisplayMessage(int index) { if (index < 35) cout << "Pleasant"; else if (index <= 60) cout << "Unpleasant"; else cout << "Health Hazard"; }

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 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(); } }}