Logical Expressions - PowerPoint PPT Presentation

1 / 53
About This Presentation
Title:

Logical Expressions

Description:

Comparing Strings ... A character-by-character comparison is made using the ASCII code of each character ... Comparing float (or double) Values ... – PowerPoint PPT presentation

Number of Views:102
Avg rating:3.0/5.0
Slides: 54
Provided by: sylvi150
Category:

less

Transcript and Presenter's Notes

Title: Logical Expressions


1
Chapter 4
  • Logical Expressions If-Else

2
Overview
  • More on Data Type bool
  • Using Relational Logical Operators to Construct
    Evaluate Logical Expressions
  • If-Else Statements
  • If Statements
  • Nested If Statements for Multi-way Branching
  • Testing a C Program

3
Boolean expressions
  • Boolean expressions (expressions of type bool)
    are constructed by using relational and logical
    operators
  • 6 Relational Operators
  • lt lt gt gt !
  • 3 Logical Operators
  • !

4
Relational operators
  • Relational operators and variables of any type
    are combined to form Boolean expressions

5
Evaluating relational expressions
  • int x 4, y 6
  • EXPRESSION VALUE
  • x lt y true
  • x 2 lt y false
  • x ! y true
  • x 3 gt y true
  • y x false
  • y x2 true
  • y x 3 7 (not Boolean)

6
Assignment expressions
  • 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 ltiostreamgt //what is the output? using
namespace std int main() int i0 cout ltlt
(i int(3.14159)) ltlt endl cout ltlt i ltlt endl
//what is the output? return 0
7
Comparing Strings
  • 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
  • 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
Comparison Operator Examples
  • string myState string yourState
  • myState Texas yourState Maryland
  • EXPRESSION VALUE
  • myState yourState false
  • myState gt yourState true
  • myState Texas true
  • myState lt texas true

9
  • Operator Meaning Associativity
  • !, , - NOT, unary , unary - Right
  • , / , Multiplication, Division, Modulus
    Left
  • , - Addition, Subtraction Left
  • lt Less than Left
  • lt Less than or equal to Left
  • gt Greater than Left
  • gt Greater than or equal to Left
  • , ! Is equal to, Is not equal to Left
  • logical AND Left
  • logical OR Left
  • Assignment Right

10
  • LOGICAL
  • EXPRESSION MEANING DESCRIPTION
  • ! 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 q p q is false if
    both
  • p and q are false. It is true
    otherwise.

11
Logical Expression Examples
  • int age bool isSenior, hasFever
  • float temperature
  • age 20 temperature 102.0
  • isSenior (age gt 55)//isSenior is false
  • hasFever (temperature gt 98.6)
  • // hasFever is true
  • EXPRESSION VALUE
  • isSenior hasFever false
  • isSenior hasFever true
  • !isSenior true
  • !hasFever false

12
What is the value?
  • int age, height
  • age 25
  • height 70
  • EXPRESSION VALUE
  • !(age lt 10) ?
  • !(height gt 60) ?

13
Short-Circuit Evaluation
  • 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 gt 50) (height gt 60) //false
  • Evaluation can stop now because result of is
    only true when both sides are true
  • It is already determined that the expression will
    be false

15
What happens?
  • int age, height
  • age 25
  • height 70
  • EXPRESSION
  • ! (height gt 60) (age gt 50)
  • Does this part need to be evaluated?

16
Write an expression for each
  • taxRate is over 25 and income is less than
    20000
  • temperature is less than or equal to 75 or
    humidity is less than 70
  • age is over 21 and age is less than 60
  • age is 21 or 22

17
Some Answers
  • (taxRate gt .25) (income lt 20000)
  • (temperature lt 75) (humidity lt .70)
  • (age gt 21) (age lt 60)
  • (age 21) (age 22)

18
Short-Circuit Benefits
  • one Boolean expression can be placed first to
    guard a potentially unsafe operation in a
    second Boolean expression
  • 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 lt 1/number)
  • is evaluated first and has value false
  • The entire expression will have a value of false
  • 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
  • Boolean expression means an expression whose
    value is true or false
  • an expression is any valid combination of
    operators and operands
  • each expression has a value
  • this can lead to UNEXPECTED RESULTS
  • construct your expressions CAREFULLY
  • use of parentheses is encouraged
  • otherwise, use the precedence chart to determine
    order

21
Comparing float (or double) Values
  • do not compare float values for equality, compare
    them for near-equality.

float myNumber float yourNumber cin gtgt
myNumber cin gtgt yourNumber test
(fabs(myNumber - yourNumber) lt 0.00001) //NOT
test (myNumber yourNumber)
22
Control Structures
  • 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
  • There are 2 general types of control structures
  • Selection, also called branching
  • Repetition, also called looping

23
C Control Structures
  • Selection
  • if
  • if . . . else
  • switch
  • Repetition
  • for loop
  • while loop
  • do . . . while loop

24
Control Structures
  • use logical expressions which may include
  • 6 Relational Operators
  • lt lt gt gt !
  • 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 gt 0)
  • average total/howMany
  • cout ltlt average
  • else
  • cout ltlt No prices were entered

27
If-Else Syntax
  • if ( Expression )
  • StatementA
  • else
  • StatementB
  • NOTE StatementA and StatementB each can be a
    single statement, a null statement, or a block.

28
if ... else Provides Two-way Selection
  • between executing one of 2 clauses
  • the if clause or the else clause

TRUE
FALSE
expression
if clause
else clause
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
If-Else with blocks
  • int carDoors, driverAge
  • float premium, monthlyPayment
  • if ((carDoors 4)(driverAge gt 24))
  • premium 650.00
  • cout ltlt "LOW RISK "
  • else
  • premium 1200.00
  • cout ltlt "HIGH RISK"
  • monthlyPayment premium / 12.0 5.00

31
What happens without braces?
  • if ((carDoors 4) (driverAge gt 24))
  • premium 650.00
  • cout ltlt "LOW RISK"
  • else
  • premium 1200.00
  • cout ltlt "HIGH RISK"
  • monthlyPayment premium / 12.0 5.00
  • COMPILE ERROR OCCURS
  • The if clause is the statement following the if

32
Braces define blocks of code
  • Braces can only be omitted when each clause is a
    single statement
  • if ( lastInitial lt 45 )
  • volume 1
  • else
  • volume 2
  • cout ltlt "Look it up in volume "
  • ltlt volume ltlt "of NYC phone book"

33
If-Then-Else for a mail order
  • Assign value .25 to discountRate and assign value
    10.00 to shipCost if purchase is over 100.00
  • Otherwise, assign value .15 to discountRate and
    assign value 5.00 to shipCost
  • Either way, calculate totalBill

34
These braces cannot be omitted
  • if (purchase gt 100.00)
  • discountRate 0.25
  • shipCost 10.00
  • else
  • discountRate .15
  • shipCost 5.00
  • totalBill purchase (1- discountRate)
  • shipCost

35
If statement is a selection
  • of whether or not to execute a statement
  • which can be a single statement or a block

TRUE
expression
FALSE
statement
36
Terminating your program
  • int number
  • cout ltlt "Enter a non-zero number"
  • cin gtgt number
  • if (number 0)
  • cout ltlt "Bad input. Program terminated"
  • return 1
  • // otherwise continue processing

37
These are equivalent. Why?
  • if (number 0) if (! number)
  • . .
  • . .
  • . .
  • . .
  • Each expression is only true when number has
    value 0.

38
Write If or If-Else for each
  • If taxCode is 7, increase price by adding taxRate
    times price to it
  • If code has value 1, read values for income and
    taxRate from cin, and calculate and display
    taxDue as their product
  • 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 gtgt income gtgt taxRate
  • taxDue income taxRate
  • cout ltlt taxDue
  • if (( A gt 0)(A lt 5))
  • B 1/A
  • else
  • B A

40
What output? and Why?
  • int age
  • age 30
  • if ( age lt 18 )
  • cout ltlt Do you drive?
  • cout ltlt Too young to vote

41
What output? and Why?
  • int code
  • code 0
  • if ( ! code )
  • cout ltlt Yesterday
  • else
  • cout ltlt Tomorrow

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

43
Chained If
  • The if clause else clause of an if...else
    statement can contain any kind of statement
  • including another ifelse statement
  • 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
  • Each Expression is evaluated in sequence, until
    some Expression is found that is true
  • Only the specific Statement following that
    particular true Expression is executed
  • If no Expression is true, the Statement following
    the final else is executed
  • 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 gt 90)
  • cout ltlt "SENIOR STATUS"
  • else if (creditsEarned gt 60)
  • cout ltlt "JUNIOR STATUS"
  • else if (creditsEarned gt 30)
  • cout ltlt "SOPHOMORE STATUS"
  • else
  • cout ltlt "FRESHMAN STATUS"

47
Writing Chained if Statements
  • Display one word to describe the int value of
    number as Positive, Negative, or Zero
  • Your city classifies a pollution index
  • less than 35 as Pleasant
  • 35 through 60 as Unpleasant
  • and above 60 as Health Hazard
  • Display the correct description of the pollution
    index value

48
One Answer
  • if (number gt 0)
  • cout ltlt "Positive"
  • else if (number lt 0)
  • cout ltlt "Negative"
  • else
  • cout ltlt "Zero"

49
Other Answer
  • if ( index lt 35 )
  • cout ltlt Pleasant
  • else if ( index lt 60 )
  • cout ltlt Unpleasant
  • else
  • cout ltlt Health Hazard

50
Write a void Function
  • called DisplayMessage (which you can call from
    main) to describe the pollution index value it
    receives as an argument
  • Write a driver program to test this function
  • 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 lt 35)
  • cout ltlt "Pleasant"
  • else if (index lt 60)
  • cout ltlt "Unpleasant"
  • else
  • cout ltlt "Health Hazard"

52
The Driver Program
  • include ltiostreamgt
  • using namespace std
  • void DisplayMessage (int) //prototype
  • int main ()
  • int pollutionIndex //declare variable
  • cout ltlt "Enter air pollution index"
  • cin gtgt pollutionIndex
  • DisplayMessage(pollutionIndex) //call
  • return 0

53
Nested Decisions
if(isHungry(Lisa) isHungry(Ed))
if(isHere(Boss) isHungry(Boss))
eat(FOOD_FANCY) shiftAppts(12.0,pm,2.0,pm)
else if(isHere(Jim)
isHere(Lori)) eat(FOOD_CAFETERIA)
else
if(getTime() gt MID_DAY)
eat(FOOD_BROWNBAG) else
cancelLunch()
  • Sometimes you will need more than two parts.
  • Use nested if/else statements(can get very
    messycareful indenting helps)
Write a Comment
User Comments (0)
About PowerShow.com