In C programming, logical operators are used to perform logical operations on boolean values or expressions.
Operator | Description | Example | Result |
---|---|---|---|
&& |
AND Operator | a < b && b < c |
True if both conditions are true, False otherwise. |
|| |
OR Operator | a < b || b > c |
True if at least one condition is true, False otherwise. |
! |
NOT Operator | !(a > b) |
True if the condition is false, False otherwise. |
This program evaluates whether both conditions a < b and b < c are true. If both conditions are true, it returns 1 otherwise it returns 0.
#include <stdio.h> int main() { int a = 5, b = 10, c = 15; // Using && operator printf("Result of logical AND: %d\n", (a < b && b < c)); return 0; }
Result of logical AND: 1
This program checks if at least one of the conditions a < b or b > c is true. If either condition is true, it returns 1; otherwise, it returns 0.
#include <stdio.h> int main() { int a = 5, b = 10, c = 15; // Using || operator printf("Result of logical OR: %d\n", (a < b || b > c)); return 0; }
Result of logical OR: 1
This program negates the truth value of the expression a > b. If a > b is false, it returns 1 if true it returns 0.
#include <stdio.h> int main() { int a = 5, b = 10; // Using ! operator printf("Result of logical NOT: %d\n", !(a > b)); return 0; }
Result of logical NOT: 1
#include <stdio.h> #include <stdbool.h> int main() { int a=10, b=4; bool res = ((a == b) && printf("Short-Circuiting in Logical Operators")); return 0; }
Will Print Nothing
#include <stdio.h> #include <stdbool.h> int main() { int a=10, b=4; bool res = ((a != b) && printf("Logical AND Operator")); return 0; }
Logical AND Operator
#include <stdio.h> #include <stdbool.h> int main() { int a=10, b=4; bool res = ((a != b) || printf("Logical AND Operator")); return 0;
-------------------------------- Process exited after 0.06589 seconds with return value 0 Press any key to continue . . .
#include <stdio.h> #include <stdbool.h> int main() { int a=10, b=4; bool res = ((a == b) || printf("Logical Operator")); return 0; }
Logical Operator -------------------------------- Process exited after 0.04 seconds with return value 0 Press any key to continue . . .