C Logical Operators in Conditions

1. What are Logical Operators?

Logical operators are used to evaluate true/false conditions. In C, the main logical operators are:

Operator Symbol Description
AND && True if both conditions are true
OR `
NOT ! Inverts the boolean value (true → false, false → true)

Logical operators always return 1 (true) or 0 (false).


2. Logical AND (&&)

  • True only if both conditions are true.

#include <stdio.h>

int main() {
int age = 20;
int hasTicket = 1;

if (age >= 18 && hasTicket) {
printf("You can enter the concert.\n");
} else {
printf("You cannot enter the concert.\n");
}

return 0;
}

Output:

You can enter the concert.

Both age >= 18 and hasTicket must be true.


3. Logical OR (||)

  • True if at least one condition is true.

#include <stdio.h>

int main() {
int age = 16;
int hasParentalConsent = 1;

if (age >= 18 || hasParentalConsent) {
printf("You can attend the workshop.\n");
} else {
printf("You cannot attend the workshop.\n");
}

return 0;
}

Output:

You can attend the workshop.

Only one of the conditions needs to be true.


4. Logical NOT (!)

  • Inverts the boolean value: true → false, false → true

#include <stdio.h>

int main() {
int isRaining = 0; // 0 = false

if (!isRaining) {
printf("You can go outside.\n");
} else {
printf("Better stay indoors.\n");
}

return 0;
}

Output:

You can go outside.

!isRaining is true because isRaining is 0 (false).


5. Combining Logical Operators

  • You can combine multiple operators in a single condition.

#include <stdio.h>

int main() {
int age = 25;
int hasID = 1;
int hasTicket = 0;

if ((age >= 18 && hasID) || hasTicket) {
printf("You can enter.\n");
} else {
printf("Entry denied.\n");
}

return 0;
}

Output:

You can enter.

Parentheses are used to control evaluation order.


6. Key Points

  1. && → all conditions must be true

  2. || → at least one condition must be true

  3. ! → reverses the boolean value

  4. Combine logical operators for complex conditions

  5. Always use parentheses for clarity when mixing operators

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *