Logical Operators

Logical operators are used to combine or negate Boolean expressions. In C, there are three logical operators:

Logical AND (&&)

The logical AND operator is represented by `&&`. It evaluates to true only if both operands are true.

Example:


#include <stdio.h>
int main() {
    int a = 5, b = 10;
    if (a > 0 && b > 0) {
        printf("Both a and b are positive numbers.\n");
    }
    return 0;
}

Output

Both a and b are positive numbers.

Logical OR (||)

The logical OR operator is represented by `||`. It evaluates to true if at least one of the operands is true.

Example:

#include <stdio.h>
int main() {
    int a = -5, b = 10;
    if (a > 0 || b > 0) {
        printf("At least one of a or b is positive.\n");
    }
    return 0;
}

Output

At least one of a or b is positive.

Logical NOT (!)

The logical NOT operator is represented by `!`. It reverses the logical state of its operand.

Example:

#include <stdio.h>
int main() {
    int a = 5;
    if (!(a < 0)) {
        printf("a is not a negative number.\n");
    }
    return 0;
}

Output

a is not a negative number.

Combining Logical Operators

You can also combine logical operators in a single condition.

Example:

#include <stdio.h>
int main() {
    int a = 5, b = -10, c = 0;
    if (a > 0 && (b < 0 || c == 0)) {
        printf("a is positive, and either b is negative or c is zero.\n");
    }
    return 0;
}

Output

a is positive, and either b is negative or c is zero.