Logical Operators

Often we need to combine multiple different requirements in conditions. This is what logical operators are for:

  • && - logical AND (and at the same time)
  • || - logical OR (or)

The && (AND) operator:

int age = 20;
bool hasLicense = true;

// Both conditions must be true
if (age >= 18 && hasLicense) {
    std::cout << "Can drive a car" << std::endl;
}

The || (OR) operator:

std::string day = "friday";
std::string weather = "rain";

// At least one condition needs to be true
if (day == "friday" || weather == "sunny") {
    std::cout << "Going outside" << std::endl;
}

We can combine multiple operators:

int age = 25;
bool hasLicense = true;
bool hasCar = false;

// Must be adult AND have license AND (own car OR have borrowed car)
if (age >= 18 && hasLicense && (hasCar || hasBorrowedCar)) {
    std::cout << "Can go on a trip" << std::endl;
}

For better readability, we can split complex conditions into multiple variables:

bool isAdult = (age >= 18);
bool hasPermission = (hasLicense && hasExperience);
bool hasTransport = (hasCar || hasBorrowedCar);

if (isAdult && hasPermission && hasTransport) {
    std::cout << "Can go on a trip" << std::endl;
}

Instructions

Complete the if statement condition that prints Welcome if the username is admin and (and) the password is 123456.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/10

Logical Operators | Start Coder