We use logical operators to test multiple conditions.
Logical expressions produce nonzero (true) or zero (false) values.
There are three logical operators in C language.
operator | meanings |
---|---|
&& | logical AND |
|| | logical OR |
! | logical NOT |
If both operands are nonzero (true), the logical AND and && operators will give a nonzero (true) value.
Otherwise, it returns zero (false).
Truth table for logical AND operator.
A | B | A && B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
In the example below, we are checking if both logical expressions are true.
If they are, then we will execute the if block, otherwise the else block.
#include <stdio.h> int main(void) { int logical_expression_1 = 10 > 0; //this will give non-zero (true) value int logical_expression_2 = 20 <= 100; //this will give non-zero (true) value if (logical_expression_1 && logical_expression_2) { printf("Success\n"); } else { printf("No!!!\n"); } return 0; }
Success
If either operand is not zero (true), then the logical or "||" The operator will give a nonzero (true) value.
If both are zero, it returns zero (false).
A truth table of logical or operator values.
A | B | A || B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
In the following example, we are checking whether either of the two logical expressions is non-zero (true).
If true, we will execute the if block, otherwise we will execute the else block.
#include <stdio.h> int main(void) { int logical_expression_1 = 10 > 0; //this will give non-zero (true) value int logical_expression_2 = 20 >= 100; //this will give zero (false) value if (logical_expression_1 || logical_expression_2) { printf("Success\n"); } else { printf("No!!!\n"); } return 0; }
Success
If the operand is zero (false), then the logic "! The operator will give a non-zero (true) value.
If the operand is not zero (true), it returns a zero (false) value.
Logical non-operators are used with only one operand.
Truth table for logical NOT operator.
A | !A |
---|---|
0 | 1 |
1 | 0 |
example:
#include <stdio.h> int main(void) { int logical_expression = 10 < 0; //this will give zero (false) value if (!logical_expression) { printf("Success\n"); } else { printf("No!!!\n"); } return 0; }
Success