Combining Conditions: &&, || and !

OperatorNameTrue when...
&&ANDboth sides are true
||ORat least one side is true
!NOTthe condition is false (it flips it)

AND: &&

#include <iostream>
using namespace std;

int main() {
    int age = 25;
    bool hasTicket = true;
    if (age >= 18 && hasTicket) {
        cout << "Welcome to the concert!\n";
    }
    int hour = 14;
    if (hour >= 9 && hour < 17) {
        cout << "The shop is open.\n";
    }
    return 0;
}

Output

Welcome to the concert!
The shop is open.

OR: ||

#include <iostream>
#include <string>
using namespace std;

int main() {
    string day = "Sunday";
    if (day == "Saturday" || day == "Sunday") {
        cout << "Weekend! No work.\n";
    } else {
        cout << "Work day.\n";
    }
    return 0;
}

Output

Weekend! No work.

NOT: !

#include <iostream>
using namespace std;

int main() {
    bool isLoggedIn = false;
    if (!isLoggedIn) {
        cout << "Please log in first.\n";
    }
    return 0;
}

Output

Please log in first.

Think of it like this: AND is a strict security guard: you need your ID and your ticket. OR is a friendly one: your ID or your ticket is enough.

Common mistake: Writing if (1 < x < 10) like in maths. It doesn't work in C++. Write if (x > 1 && x < 10).

HOME LABS COMMUNITY DASHBOARD