C++ Logical Operators

Logical operators in C++ are used to evaluate relationships between conditions. They return a boolean value, which can either be true (1) or false (0). These operators are often combined with comparison operators to build complex decision-making logic.

Tutorials dojo strip



Logical Operators and Their Functions

OperatorNameDescriptionExample
&&Logical ANDReturns true if both conditions are truex > 50 && x < 100
||Logical ORReturns true if at least one condition is truex > 50 || x < 30
!Logical NOTReverses the result; returns false if the condition is true!(x > 50)




Using Logical Operators Example

#include <iostream>
using namespace std;

int main() {
    int bikeSpeed = 120;
    int carSpeed = 150;

    // Logical AND
    if (bikeSpeed > 100 && carSpeed > 140) {
        cout << "Both bike and car are fast.";
    }

    // Logical OR
    if (bikeSpeed > 130 || carSpeed > 140) {
        cout << "\nAt least one vehicle is fast.";
    }

    // Logical NOT
    if (!(bikeSpeed > 130)) {
        cout << "\nThe bike is not exceeding 130 km/h.";
    }

    return 0;
}

Explanation of the Example

  1. Logical AND (&&):
    • The first if statement checks if both bikeSpeed is greater than 100 and carSpeed is greater than 140.
    • If both are true, it prints: “Both bike and car are fast.”
  2. Logical OR (||):
    • The second if statement evaluates if either bikeSpeed exceeds 130 or carSpeed exceeds 140.
    • If at least one is true, it prints: “At least one vehicle is fast.”
  3. Logical NOT (!):
    • The final if statement reverses the condition. It checks if bikeSpeed is not greater than 130.
    • If true, it prints: “The bike is not exceeding 130 km/h.”

Tutorials dojo strip
Scroll to Top