0
0
C++programming~5 mins

Logical operators in C++

Choose your learning style9 modes available
Introduction

Logical operators help you combine or change true/false conditions in your program. They let you make decisions based on multiple checks.

Checking if a number is between two values (like age between 18 and 30).
Deciding if a user input is valid by checking multiple rules.
Running code only if two or more conditions are true at the same time.
Repeating a task while a condition is true or until a condition becomes true.
Skipping code if a certain condition is false.
Syntax
C++
&&  // Logical AND
||  // Logical OR
!   // Logical NOT

AND (&&) is true only if both sides are true.

OR (||) is true if at least one side is true.

NOT (!) flips true to false and false to true.

Examples
This checks if both a and b are positive numbers.
C++
if (a > 0 && b > 0) {
    // code runs if both a and b are greater than 0
}
This runs if either x equals 10 or y equals 20.
C++
if (x == 10 || y == 20) {
    // code runs if x is 10 or y is 20 (or both)
}
This runs when isReady is false, using NOT operator.
C++
if (!isReady) {
    // code runs if isReady is false
}
Sample Program

This program uses logical operators to decide if someone can enter based on age and ID, if they can go outside depending on rain or umbrella, and whether to turn on the light if it is off.

C++
#include <iostream>

int main() {
    int age = 25;
    bool hasID = true;

    if (age >= 18 && hasID) {
        std::cout << "Entry allowed" << std::endl;
    } else {
        std::cout << "Entry denied" << std::endl;
    }

    bool isRaining = false;
    bool hasUmbrella = true;

    if (isRaining && !hasUmbrella) {
        std::cout << "Better stay inside" << std::endl;
    } else {
        std::cout << "You can go outside" << std::endl;
    }

    bool lightOn = false;
    if (!lightOn) {
        std::cout << "Turn on the light" << std::endl;
    }

    return 0;
}
OutputSuccess
Important Notes

Remember that && stops checking if the first condition is false (short-circuit).

Similarly, || stops checking if the first condition is true.

Use parentheses to group conditions clearly and avoid confusion.

Summary

Logical operators combine true/false checks to control program flow.

&& means both conditions must be true.

|| means at least one condition is true.

! flips true to false and false to true.