Logical operators in C are used to perform logical operations on Boolean values (true or false). There are three main logical operators: AND (&&
), OR (||
), and NOT (!
). Here’s a detailed explanation along with examples and output for each logical operator:
1. Logical AND (&&):
Definition:
The logical AND operator (&&) returns true if both of its operands are true; otherwise, it returns false.
Example:
#include <stdio.h>
int main() {
int a = 1, b = 0;int result = (a && b);
printf(“(%d && %d) evaluates to %dn”, a, b, result);
return 0;
}
Output:
(1 && 0) evaluates to 0
2. Logical OR (||):
Definition:
The logical OR operator (||) returns true if at least one of its operands is true; otherwise, it returns false.
Example:
#include <stdio.h>
int main() {
int a = 1, b = 0;int result = (a || b);
printf(“(%d || %d) evaluates to %dn”, a, b, result);
return 0;
}
Output:
(1 || 0) evaluates to 1
.
3. Logical NOT (!):
Definition:
The logical NOT operator (!) returns true if its operand is false, and false if its operand is true. It negates the given Boolean value.
Example:
#include <stdio.h>
int main() {
int a = 1;int result = !a;
printf(“!(%d) evaluates to %dn”, a, result);
return 0;
}
Output:
!(1) evaluates to 0
Compound Logical Expressions:
Definition:
Logical operators can be combined to form more complex logical expressions.
Example:
#include <stdio.h>
int main() {
int a = 1, b = 0, c = 1;int result = (a && b) || c;
printf(“(%d && %d) || %d evaluates to %dn”, a, b, c, result);
return 0;
}
Output:
(1 && 0) || 1 evaluates to 1
These logical operators are fundamental for creating conditional statements and controlling the flow of a program based on conditions. Understanding how logical operators work is essential for writing effective and correct C programs.