Relational operators, Logical operators, and Selection

1 / 43
About This Presentation
Title:

Relational operators, Logical operators, and Selection

Description:

Boolean algebra and the bool data type. Logical expressions and Logical operators ... The branch of math that deals with this logic is called Boolean algebra ... – PowerPoint PPT presentation

Number of Views:44
Avg rating:3.0/5.0
Slides: 44
Provided by: jian9

less

Transcript and Presenter's Notes

Title: Relational operators, Logical operators, and Selection


1
Chapter 4
  • Relational operators, Logical operators, and
    Selection

2
Outline
  • One-way if control constructs
  • Relational operators
  • Two-way if control constructs
  • Boolean algebra and the bool data type
  • Logical expressions and Logical operators
  • The switch control construct (chapter 12.1)
  • Enumerated Data Types enum

3
One-Way SelectionRelational Operators
4
Basic if Construct
logical expression true or false
  • Syntax
  • if (Condition)
  • Statements
  • If the Condition is true then execute Statements
  • Statements can be either a single statement or a
    group of statements within braces
  • Example 1
  • if (NbrStudent gt 10)
  • Rate 5
  • Cost NbrStudent Rate
  • // group discount
  • Example 2
  • if (value lt 0)
  • value - value

you can omit braces for a single statement.
5
Suggestion
  • Use in C control constructs even if
    Statements is only one statement
  • Saves a lot of grief later
  • j 5
  • k 3
  • i 4
  • if (i gt 0)
  • j 0
  • k 0

6
Relational Operators
  • Ordering Operators
  • lt
  • gt
  • gt
  • lt
  • Examples
  • int i 5
  • int k 12
  • if (i lt 10) ... // true or false?
  • if (k gt i) ... // true or false?
  • if (i gt k) ... // true or false?
  • if (k lt 12) ... // true or false?

7
Examples
  • age 25
  • age 14
  • age 18

8
Relational Operators
  • Equality Operators
  • !
  • Examples
  • int i 30
  • int k 15
  • if (i k) ...
  • if (i ! k) ...

Be extra careful with this one is very
different from .
false
true
9
Misuse
A Bug Just Waiting to Bite You if (x 7) ...
Always true why?
10
Two-Way Selection
11
Two-Way if Construct
  • Syntax
  • if (Condition)
  • Statements1
  • else
  • Statements2
  • Example
  • if (B ! 0)
  • C A / B
  • else
  • C 0

12
Example
  • score 54
  • score 73

13
Using and
  • C style

if (Password "shazam") cout ltlt "Password
accepted." ltlt endl else cout ltlt
"Invalid password." ltlt endl
  • Java style (Ok!)

if (Password "shazam") cout ltlt "Password
accepted." ltlt endl else cout ltlt "Invalid
password." ltlt endl
  • Must use indentations

14
Logical Expressions The bool Data Type
15
Boolean Algebra - 1
  • Logical expressions have one of two values true,
    false
  • int I 5
  • int K 12
  • I lt 10 ... // true or false?
  • K gt I ... // true or false?
  • I ! K ... // true or false?
  • K 12 ... // true or false?
  • The branch of math that deals with this logic is
    called Boolean algebra
  • We can combine simple logical expressions using
    logical operators and, or, not

16
Boolean Algebra - 2
  • Truth Tables
  • Lists all combinations of operand values and
    the result of the operation for each combination
  • Operands P and Q are logical expressions
  • Truth Table for and

int I 5 int K 8 I lt 10 // true K
gt I // true K lt 7 // false I K
// false
Remember this shortcutfalse and anything
false
17
Boolean Algebra - 3
  • Truth Table for or
  • Truth Table for not

int I 5 int K 8 I lt 10 // true K
gt I // true K lt 7 // false I K
// false
Also remember this onetrue or anything true
18
Boolean Algebra - 4
  • Combining simple logical expressions
  • not (P and Q)
  • A truth table can be used to determine when a
    logical expression is true

19
Logical Operators
  • Logical Operators
  • The and operator is
  • The or operator is
  • The not operator is !
  • Be careful
  • and and ! are Boolean operators
  • and and are also defined they are
    the bitwise (bit-by-bit) operators
    corresponding to these Boolean operators
  • Operate on 0s 1s in a value instead of on false
    true
  • Lots of uses for them in system-level programming
  • We wont talk more about them in this course

(the exclamation mark)
20
Operator Precedence Revisited
  • Precedence of operators (high to low)
  • Parentheses ( )
  • Unary operators - ! --
  • Multiplicative operators /
  • Additive operators -
  • Relational ordering lt lt gt gt
  • Relational equality !
  • Bitwise and
  • Bitwise or
  • Logical and
  • Logical or
  • Assignment - /

Differentprecedences
And assignmentis way down there
21
Compound Logical Expressions
  • The Great Temptation
  • What if you want to say the value of height
    between 65 and 75
  • In math, we could write 65 lt height lt 75
  • BUT in programming ...
  • If we say if (65 lt height lt 75) ... we get a
    syntax error!
  • We have to say if (65 lt height height lt
    75) ...or we can say if (75 gt height
    height gt 65) typo on P70

22
Example - 1


23
Example - 2
Using !
! (65 lt height height lt 75)
! (P Q) ?? ! P ! Q ! (P Q) ?? !
P ! Q
65 gt height height gt75
24
The bool Data Type
  • bool Variables
  • Variables that can take on one of these two
    values
  • true
  • false
  • Declaring bool Variables
  • Just like you declare any other variable
  • bool bIsPositiveNumber
  • bool Flag false
  • Using bool Variables
  • Assign to them bIsPositiveNumber (5 gt 0)
  • Test their value if (! bIsPositiveNumber )

C keywords, written just like that
(returns a bool value)
25
bool vs. Numeric Values
  • bool is compatible with numeric data types
  • Converting from bool to int
  • false converts to 0
  • true converts to 1
  • Converting from int to bool
  • Zero converts to false
  • ANY non-zero value converts to true
  • This is why if (I 0) always fails!
  • And, of course, the same is true for any
    other numeric data type

26
Example - 3
Whats wrong?
short-circuit evaluation
27
Multi-Way Selection
28
Nested if Selection
  • The branch of an if statement is itself an if
    statement

if (x gt y) cout ltlt x is larger
else if (x lt y) cout
ltlt y is larger else
cout ltlt x equals y"
  • Use if you are confused

29
if /else if /else Construct
30
Multiple Selections if else if else
(Because of precedence rules, theinner ( ) are
just for documentation.)
  • if ((Grade 'A')
  • (Grade 'B')
  • (Grade 'C'))
  • cout ltlt "Pass." ltlt endl
  • else if (Grade 'D')
  • cout ltlt Borderline." ltlt endl
  • else if (Grade 'F')
  • cout ltlt "Fail." ltlt endl
  • else
  • cout ltlt " Invalid Grade value!" ltlt endl

false
if
true
false
else if
true

(Defensive programming)
false
else
true
31
Multiple Selections
  • switch
  • switch (Grade)
  • case 'A' case 'B' case 'C'
  • cout ltlt "Pass." ltlt endl
  • break
  • case 'D'
  • cout ltlt Maybe." ltlt endl break
  • case 'F'
  • cout ltlt Fail." ltlt endl break
  • default
  • cout ltlt "Error!" ltlt endl
  • if else-if else
  • if ((Grade 'A')
  • (Grade 'B')
  • (Grade 'C'))
  • cout ltlt "Pass." ltlt endl
  • else if (Grade 'D')
  • cout ltlt Maybe." ltlt endl
  • else if (Grade 'F')
  • cout ltlt "Fail." ltlt endl
  • else
  • cout ltlt "Error!" ltlt endl

Dont need around this.
32
Syntactic Details of the switch
  • switch (Expression)
  • case Constant ... case Constant
  • Statements
  • break
  • ...
  • case Constant ... case Constant
  • Statements
  • break
  • default Statements
  • // end case

(Optional as manyConstants as needed)
(No need for statements delimitedby the
case lines)
(To keep control from fallingthrough to the next
group)
(As many case blocksas needed)
(Optional done if none ofthe cases gets
executed)
33
Why break?
  • A diagram showing the control flow of the switch
    statement with and without the break statements.

34
Whats the Difference
  • between the ifelse ifelse and switch?
  • The ifelse ifelse is more general
  • Example can we do this with a switch?
  • If I is not zero, then write out the current
    value of I
  • Else if J is not zero, then write out the current
    value of J
  • Otherwise write out the current value of K
  • Answer No!
  • Why not?
  • Because a switch has to make all its decisions
    based on the value of the one expression
  • We have to use ifelse ifelse to do the job above

35
Nesting if Groups
  • Example at Top of Page 77 in Text
  • Omits the and not a good style,
    re-coded safely
  • if (age lt 19)
  • if (points lt 6)
  • cout ltlt OK ltlt endl
  • else
  • cout ltlt Test ltlt endl
  • else // Age gt 19
  • if (points lt 9)
  • cout ltlt OK ltlt endl
  • Why add the extra structure?
  • So you make fewer mis-takes in your code.
  • So you dont destroy yourprograms logic if you
    haveto add another statementto any of the
    blocks.
  • So you minimize your 3AMdebugging sessions.

36
More about multiway selection
  • This works
  • Score 92
  • if (Score lt 60)
  • cout ltlt Fail" ltlt endl
  • if (score gt 60)
  • cout ltlt Pass" ltlt endl
  • But this is better
  • Score 92
  • if (Score lt 60)
  • cout ltlt Fail" ltlt endl
  • else if (score gt 60)
  • cout ltlt Pass" ltlt endl
  • Why?

37
Simplify you solution
  • Problem If Num lt 0, print Negative if Num is
    between 0 and 99 (inclusive), print OK else
    print Big
  • Write the if else if else in that order
  • What does the else if in the set look like?
  • else if (Num gt 0 Num lt 99)
  • How can we simplify the situation?
  • Look at the ranges differently
  • if (Num lt 0)
  • cout ltlt "Negative" ltlt endl
  • else if (Num gt 99)
  • cout ltlt "Big" ltlt endl
  • else
  • cout ltlt "OK" ltlt endl

38
EnumeratedData Types
39
Enumerated Data Types
  • Details in Textbook, 12.3, pages 277-81
  • Purpose
  • Define new data types of our own
  • Data types constants are English words
  • Example
  • Define a gender data type, whose constants
    are MALE FEMALE
  • Called an enumerated data type because its
    values are words, listed (enumerated) explicitly
  • Were free to use any identifiers for both the
    data type name and the constant names
  • Providing, of course, they arent already in use

40
Examples
In this case, the afterthe is necessary.
  • That gender Data Type
  • The declaration code
  • enum gender MALE, FEMALE // end enum
  • Using our new data type
  • gender Applicant1_Gender // declaration
  • gender Applicant2_Gender
  • . . .
  • Applicant1_Gender MALE // assignment
  • Applicant2_Gender FEMALE

41
Enumerated Data Types
  • Exercise
  • define an enumerated data type named month
    that has constants JAN, FEB, ..., DEC
  • enum month JAN, FEB, MAR, APR, MAY, JUN,
    JUL, AUG, SEP, OCT, NOV, DEC
  • Then, can I say
  • month ThisMonth
  • ThisMonth SEP
  • if (ThisMonth lt DEC) // whatever ?
  • Yes!The order you list them in IS the ordering
    of the values.

42
Major Activities in Software Development
  • Requirements analysis
  • Understand the requirements specification (or
    wish list)
  • Deduce the real job from the given requirements
  • Program design
  • Break the requirements down into manageable
    pieces
  • Further subdivide those pieces if necessary
  • Program development
  • Coding actually writing the program
  • Testing
  • Think up complete sets of test cases
  • Legal and illegal input values boundary values
  • Write test program to exercise your program on
    test cases
  • Pay attention to test outputs fix the program
    if necessary

43
Developing Programs
  • Textbook Section 4.6
  • Reviews those 4 steps in more detail
  • READ the two examples on pages 80-85
  • Well run through an example problem in detail
    after weve covered all the control constructs
  • Analysis
  • Design
  • Coding
  • Testing
Write a Comment
User Comments (0)