Logical Operators Part 2
Part of the Fundamentals section of Coddy's C journey — lesson 22 of 63.
Logical operators have a special table called a "Truth table" that shows what the combination of logical operators returns.
Truth table for the and (&&) operator:
| a | b | a && b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
The only way to get a 1 (true) for the and (&&) operator is if both a and b are 1 (true)
Truth table for the or (||) operator:
| a | b | a || b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
In this case, to get a 1 (true) result, either a or b should be 1 (true).
Truth table for the not (!) operator:
| a | !a |
|---|---|
| 0 | 1 |
| 1 | 0 |
Here, the value of a is reversed. If a is 0 (false) then !a is 1 (true)
Challenge
EasyYou need to assign integer values to variables b1 and b2 so that b3 evaluates to 1 (true) in the expression: int b3 = !((b1 + b2) > (b1 * b2));
Take a moment to analyze the condition and think about what values would make it true.
Cheat sheet
Truth tables show the results of logical operators:
AND (&&) operator:
| a | b | a && b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
Returns 1 (true) only when both operands are 1 (true).
OR (||) operator:
| a | b | a || b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
Returns 1 (true) when either operand is 1 (true).
NOT (!) operator:
| a | !a |
|---|---|
| 0 | 1 |
| 1 | 0 |
Reverses the value: 0 (false) becomes 1 (true) and vice versa.
Try it yourself
#include <stdio.h>
int main() {
// Type your code below
int b1 = ?;
int b2 = ?;
int b3 = !((b1 + b2) > (b1 * b2));
// Don't change the line below
printf("b3 = %d\n", b3);
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge