C Programming
In this tutorial we will learn about logical operators in C programming language.
We use the logical operators to test more than one condition.
Logical expressions yields either non-zero (true) or zero (false) value.
There are three logical operators in C.
Operator | Description |
---|---|
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
Click here to learn about Boolean Algebra.
The logical AND &&
operator will give non-zero (true) value if both the operands are non-zero (true). Otherwise, it will return zero (false).
Truth table of logical AND operator.
A | B | A && B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
In the following example we are checking if the two logical expressions are both 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;
}
Output
Success
The logical OR ||
operator will give non-zero (true) value if any one of the operand is non-zero (true). If both are zero then it will return zero (false).
Truth table of logical OR operator.
A | B | A || B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
In the following example we are checking if any one of the two logical expressions is non-zero (true). If yes, 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 zero (false) value
if (logical_expression_1 || logical_expression_2) {
printf("Success\n");
}
else {
printf("No!!!\n");
}
return 0;
}
Output
Success
The logical NOT !
operator will give non-zero (true) value if the operand is zero (false). And it will return zero (false) value if the operand is non-zero (true).
Logical NOT operator works with only one operand.
Truth table of logical NOT operator.
A | !A |
---|---|
0 | 1 |
1 | 0 |
In the following example we are checking if the logical expression is zero (false). If yes, then we will execute the if-block otherwise, the else-block.
#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;
}
Output
Success
ADVERTISEMENT