03 Logical Operators
03 Logical Operators
Logical Operators
with Sir Beets
What we learned before: Test precisely 1 condition only
Relational Operators: > >= < <==
Equality Operators: == !=
Logical
Logical Operators for testing multiple conditions
Operators Logical AND ( && ) both conditions must be true
Logical OR ( || ) either or both conditions are true
Logical Negation ( ! ) reverse the meaning of the condition
1. Input N
2. If ( N > 0 && N%2 == 0 )
2.1 Then display “Positive even number”
2.2 Else display “Negative or an odd number”
N N>0 N % 2 == 0 Display
Example 1 true false Negative or an odd number
0 false true Negative or an odd number
-1 false false Negative or an odd number
-1200 false true Negative or an odd number
3464 true true Positive even number
8 true true Positive even number
17 true false Negative or an odd number
Start Start
N N
Is, false
N>0
Is, false
?
Logical
true
N>0 &&
N%2==0
Operator
Is, false ?
N%2==0
Flowchart
?
true true
Positive Positive
even Negative or Negative or
even
number an odd an odd
number
End End
&& has higher precedence than II
Short-Circuit Both associate from left to right
Evaluation
Stops when truth or falsehood in first condition is known
1. Input N
2. If ( N > 0 && N%2 == 0 )
2.1 Then display “Positive even number”
2.2 Else display “Negative or an odd number”
#include <stdio.h>
Pseudocode void main() {
int DurianCount;
float DurianWeight;
if ( DurianCount == 4 && DurianWeight >= 6.27 ) {
printf(“Lovely”);
} else {
printf(“Return them”);
}
}