Logical operators in C language

 Logical operators are used to evaluate conditions that return true or false.

There are three logical operators in C:

  1. AND (&&)
  2. OR (||)
  3. NOT (!)

Here is a table that summarizes the logical operators in C language:

Operator
Description
Example
&&
AND
x > 0 && y > 0
||
OR
x > 0 || y > 0
!
NOT
!(x > 0 && y > 0)

AND operator (&&)

The AND operator (&&) returns true only if both conditions being evaluated are true.

Example:

int x = 5, y = 10;
if (x > 0 && y > 0) {
    printf("Both x and y are positive\n");
}

In this example, the condition (x > 0 && y > 0) is true because both x and y are positive. If either x or y were negative, the condition would evaluate to false.

OR operator (||)

The OR operator (||) returns true if at least one of the conditions being evaluated is true.

Example:

int x = 5, y = -10;
if (x > 0 || y > 0) {
    printf("At least one of x and y is positive\n");
}

In this example, the condition (x > 0 || y > 0) is true because x is positive, even though y is negative. If both x and y were negative, the condition would evaluate as false.

NOT operator (!)

The NOT operator (!) is used to invert the value of a condition.

Example:

int x = 5, y = 10;
if (!(x > 0 && y > 0)) {
    printf("Either x or y is not positive\n");
}

In this example, the condition !(x > 0 && y > 0) is false because both x and y are positive. If either x or y was negative, the condition would evaluate to true.