Logical operators in C programming

Logical Operators in C

Logical Operators in C

Logical operators in C are used to perform logical operations on expressions. They are commonly used in conditional statements and loops to control the flow of the program based on boolean conditions. Here’s a guide to the logical operators available in C:

1. Logical AND Operator (&&)

The && operator checks if both conditions are true. It returns true if both operands are true; otherwise, it returns false.

int a = 5;
int b = 10;
if (a < 10 && b > 5) {
    printf("Both conditions are true");
} else {
    printf("At least one condition is false");
}

2. Logical OR Operator (||)

The || operator checks if at least one of the conditions is true. It returns true if at least one operand is true; otherwise, it returns false.

int a = 5;
int b = 10;
if (a < 10 || b < 5) {
    printf("At least one condition is true");
} else {
    printf("Both conditions are false");
}

3. Logical NOT Operator (!)

The ! operator negates the value of a condition. It returns true if the operand is false and false if the operand is true.

int a = 5;
if (!(a > 10)) {
    printf("a is not greater than 10");
} else {
    printf("a is greater than 10");
}

Logical Operators Summary

Operator Description Example Returns
&& Logical AND (a < 10 && b > 5) true if both conditions are true
|| Logical OR (a < 10 || b < 5) true if at least one condition is true
! Logical NOT !(a > 10) true if the condition is false
Note: Logical operators are essential for controlling the flow of your program based on multiple conditions. They help create more complex decision-making logic.

Comments

Popular Posts