Logical operators: &&, ||, !
Logical operators in C programming are used to perform logical operations on boolean expressions or conditions. They allow you to combine multiple conditions and evaluate the result. Here are the logical operators in C:
1. Logical AND (&&):
The `&&` operator returns `1` (true) if both the left and right operands are true. Otherwise, it returns `0` (false).
Example:
int result = (5 > 3) && (4 < 6); // result is 1 (true)
2. Logical OR ( || ):
The `||` operator returns `1` (true) if either the left or right operand is true. If both operands are false, it returns `0` (false).
Example:
int result = (5 > 3) || (4 > 6); // result is 1 (true)
3. Logical NOT (!):
The `!` operator negates the value of the operand. If the operand is true, it returns `0` (false). If the operand is false, it returns `1` (true).
Example:
int result = !(5 > 3); // result is 0 (false)
Logical operators are typically used in conditional statements (`if`, `while`, `for`) to evaluate multiple conditions and make decisions based on the logical result. They are useful for combining multiple comparisons and creating complex conditions.
Example:
int num = 5;
if (num > 0 && num < 10) {
// Execute this block if num is greater than 0 and less than 10
printf("num is between 0 and 10\n");
}
int flag1 = 1;
int flag2 = 0;
if (flag1 || flag2) {
// Execute this block if either flag1 or flag2 is true
printf("At least one flag is true\n");
}