Logical Operators

In C programming, logical operators are used to perform logical operations on boolean values (i.e., values that are either true or false). C provides three main logical operators:

  1. && (logical AND)
  2. || (logical OR)
  3. ! (logical NOT).
These operators allow you to combine and manipulate boolean expressions in your programs. Here's a brief overview of each logical operator in C:

Logical AND (&&):

Syntax: expression1 && expression2 Description: This operator returns true (1) if both expression1 and expression2 are true; otherwise, it returns false (0). Example:
if (x > 0 && y < 10) {
// This block will execute if both conditions are true.
}

Logical OR (||):

Syntax: expression1 || expression2 Description: This operator returns true (1) if either expression1 or expression2 (or both) is true; it returns false (0) only if both are false. Example:
if (x > 0 || y < 10) {
// This block will execute if at least one of the conditions is true.
}

Logical NOT (!):

Syntax: !expression
Description: This operator negates the value of expression. If expression is true, !expression becomes false, and if expression is false, !expression becomes true. Example:
if (!flag) {
// This block will execute if 'flag' is false.
}
These logical operators are often used in conditional statements (e.g., if, while, for) to control the flow of your program based on certain conditions. They allow you to build complex conditions by combining multiple boolean expressions. Here's a simple example using logical operators in an if statement:
int age = 25;
int isStudent = 1;
if (age >= 18 && !isStudent) {
printf("You are an adult.");
} else {
printf("You are either under 18 or a student.");
}
In this example, the && operator combines the conditions age >= 18 and !isStudent, and the ! operator negates the value of isStudent. The program will print the appropriate message based on the combined condition.