0
0
Cprogramming~5 mins

Logical operators

Choose your learning style9 modes available
Introduction
Logical operators help you make decisions by combining true or false conditions.
Checking if two conditions are both true, like if you have enough money and time to buy something.
Deciding if at least one condition is true, like if you are hungry or thirsty.
Making sure a condition is not true, like if a door is not locked before opening it.
Syntax
C
expression1 && expression2  // AND operator
expression1 || expression2  // OR operator
!expression               // NOT operator
&& means AND: true only if both expressions are true.
|| means OR: true if at least one expression is true.
! means NOT: reverses true to false and false to true.
Examples
Checks if a person is an adult and has an ID.
C
if (age >= 18 && hasID) {
    // code runs if age is 18 or more AND hasID is true
}
Runs code if either condition is true.
C
if (isSunny || isWeekend) {
    // code runs if it is sunny OR it is weekend
}
Runs code only when it is not raining.
C
if (!isRaining) {
    // code runs if it is NOT raining
}
Sample Program
This program uses logical operators to decide if someone can enter a club, if they can go outside, and if they should take an umbrella.
C
#include <stdio.h>

int main() {
    int age = 20;
    int hasID = 1; // 1 means true, 0 means false
    int isSunny = 0;
    int isWeekend = 1;

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

    if (isSunny || isWeekend) {
        printf("You can go outside.\n");
    } else {
        printf("Better stay inside.\n");
    }

    if (!isSunny) {
        printf("Don't forget your umbrella!\n");
    }

    return 0;
}
OutputSuccess
Important Notes
In C, 0 means false and any non-zero value means true.
Logical operators evaluate expressions from left to right and stop early if the result is known (short-circuit).
Use parentheses to group conditions clearly.
Summary
Logical operators combine true/false conditions to make decisions.
&& means AND, || means OR, and ! means NOT.
They help control the flow of your program based on multiple conditions.