Types of Logical Operators
1. Logical AND Operator ( && )
If both operands are non zero then the condition becomes true. Otherwise, the result has a value of 0. The return type of the result is int. Below is the truth table for the logical AND operator.
X |
Y | X && Y |
---|---|---|
1 |
1 |
1 |
1 |
0 |
0 |
0 |
1 |
0 |
0 |
0 |
0 |
Syntax
(operand_1 && operand_2)
Example
C
// C program for Logical // AND Operator #include <stdio.h> // Driver code int main() { int a = 10, b = 20; if (a > 0 && b > 0) { printf ( "Both values are greater than 0\n" ); } else { printf ( "Both values are less than 0\n" ); } return 0; } |
Both values are greater than 0
2. Logical OR Operator ( || )
The condition becomes true if any one of them is non-zero. Otherwise, it returns false i.e., 0 as the value. Below is the truth table for the logical OR operator.
X | Y | X || Y |
---|---|---|
1 |
1 |
1 |
1 |
0 |
1 |
0 |
1 |
1 |
0 |
0 |
0 |
Syntax
(operand_1 || operand_2)
Example
C
// C program for Logical // OR Operator #include <stdio.h> // Driver code int main() { int a = -1, b = 20; if (a > 0 || b > 0) { printf ( "Any one of the given value is " "greater than 0\n" ); } else { printf ( "Both values are less than 0\n" ); } return 0; } |
Any one of the given value is greater than 0
3. Logical NOT Operator ( ! )
If the condition is true then the logical NOT operator will make it false and vice-versa. Below is the truth table for the logical NOT operator.
X | !X |
---|---|
0 |
1 |
1 |
0 |
Syntax
!(operand_1 && operand_2)
Example
C
// C program for Logical // NOT Operator #include <stdio.h> // Driver code int main() { int a = 10, b = 20; if (!(a > 0 && b > 0)) { // condition returned true but // logical NOT operator changed // it to false printf ( "Both values are greater than 0\n" ); } else { printf ( "Both values are less than 0\n" ); } return 0; } |
C Logical Operators
Logical operators in C are used to combine multiple conditions/constraints. Logical Operators returns either 0 or 1, it depends on whether the expression result is true or false. In C programming for decision-making, we use logical operators.
We have 3 logical operators in the C language:
- Logical AND ( && )
- Logical OR ( || )
- Logical NOT ( ! )