Logical operators are used to perform logical operations of given expressions [relational expressions] or variables.
There are three logical operators available in C. Let’s discuss one by one.
|| [Logical OR] operator
If one of the operands or expressions is true, it will return 1.
If all of them are false, it will return 0.
0 | 0 | 0 | [5 > 10] || [5 < 4] Both expressions are false. so, logical OR output will be 0 |
0 | 1 | 1 | [10 > 20] || [10 < 20] First expression is false and second one is true. so, logical OR output will be 1 |
1 | 0 | 1 | [10 < 20] || [10 > 100] First expression is true and second one is false. so, logical OR output will be 1 |
1 | 1 | 1 | [10 < 20] || [10 < 100] Both expressions are true. so, logical OR output will be 1 |
&& [Logical AND] operator
If both left and right operands or expressions are true, it will return true. Otherwise, it will return false.
Note, non-zero value operands are considered as true.
0 | 0 | 0 | [5 > 10] && [5 < 4] Both expressions are false. so, logical AND output will be 0 |
0 | 1 | 0 | [10 > 20] && [10 < 20] First expression is false and second one is true. so, logical AND output will be 0 |
1 | 0 | 0 | [10 < 20] && [10 > 100] First expression is true and second one is false. so, logical AND output will be 0 |
1 | 1 | 1 | [10 < 20] && [10 < 100] Both expressions are true. so, logical AND output will be 1 |
! [Logical NOT] operator
Logical NOT operator is used to inverse the current decision. Say, if current state is true, Logical NOT [!] operator will make it false.
0 | 1 | ![100 < 10] 100 is greater than 10. So, it will return false. |
1 | 0 | ![10 < 100] 10 is less than 100. So, it will return true. |
Sample Program
Example
#include int main[] { int a = 5, b = 10 ,ret; ret = [ [a true. So, 1 || 1 will return 1. printf["Return value of above expression is %d\n",ret]; ret = [ [ a true. 5 == 10 ==> false. So, 1 && 0 will return 0; printf["Return value of above expression is %d\n",ret]; ret = ! [ [ a a && a > 0]{ //do something... }
Note that:
- a && b will return true only when BOTH a AND b are true.
- a || b will return true when either a AND/OR b are true.
Challenge
As briefly mentioned in About Programming, computers ultimately calculate just by doing simple logical operation like AND and OR on Logic Gates. While these gates are physical parts of a computer, you can simulate them in software. The NAND gate is a logical gate that returns false only when both its inputs are true. In other cases it returns true. You will simulate a NAND gate in this challenge. Try to do this challenge
without using any if statements.