Logical Operators — Combining Conditions
Learn to combine conditions with AND, OR, and NOT — the building blocks of powerful decision-making!
Open interactive version (quiz + challenge)Real-world analogy
Logical operators are like rules at a fancy party. AND (&&) means you need BOTH a ticket AND an ID to enter — missing either one and you are turned away. OR (||) means you need a ticket OR be on the VIP list — having either one is enough. NOT (!) flips things — if the door says 'NOT members only,' then non-members CAN enter. These three little operators let you build any rule you can imagine!
What is it?
Logical operators let you combine multiple conditions into one. AND (&&) requires all conditions to be true. OR (||) requires at least one to be true. NOT (!) flips true to false and vice versa. Together, they let you express any complex condition your program needs.
Real-world relevance
Logical operators power everything with rules. Email filters: if (from == boss && subject contains 'urgent'), mark as important. Search engines: 'cats AND dogs' finds pages with both words, 'cats OR dogs' finds pages with either. In CP, you combine conditions to check ranges, validate input, and handle edge cases — they appear in virtually every problem.
Key points
- && (AND) — Both Must Be True — The && operator returns true ONLY if BOTH sides are true. true && true = true. true && false = false. false && true = false. false && false = false. Example: if (age >= 18 && hasLicense) — you can drive only if you are 18+ AND have a license. Both conditions must pass!
- || (OR) — At Least One Must Be True — The || operator returns true if AT LEAST ONE side is true. true || true = true. true || false = true. false || true = true. false || false = false. Only when BOTH are false does || give false. Example: if (isWeekend || isHoliday) — you get a day off if it is a weekend OR a holiday (or both!).
- ! (NOT) — Flip True to False — The ! operator flips a boolean value. !true = false. !false = true. Example: if (!gameOver) means 'if the game is NOT over.' You can also use it with comparisons: !(a == b) is the same as (a != b). The NOT operator is like flipping a light switch.
- Short-Circuit Evaluation — C++ Is Lazy! — C++ is clever (lazy) about evaluating conditions. For &&, if the LEFT side is false, it does not even check the right side — because the result is false no matter what. For ||, if the LEFT side is true, it skips the right side. This is called 'short-circuit evaluation.' It is not just efficient — it can prevent crashes! Example: if (n != 0 && 100/n > 5) is safe because if n is 0, the division never happens.
- Combining Multiple Operators — You can chain logical operators: if (a > 0 && a = 18 && hasTicket) || isVIP) — adults with tickets or VIPs can enter. Use parentheses to make the order clear!
- Operator Precedence — ! Before && Before || — Without parentheses: ! is evaluated first, then &&, then ||. So 'true || false && false' means 'true || (false && false)' = 'true || false' = true. This can be confusing! ALWAYS use parentheses when mixing && and || to make your intention crystal clear. Your future self will thank you.
- CP Pattern — Range Checking — A super common CP pattern is checking if a value is in a range: if (x >= L && x = 0 && x = 0 && y < m). This is essential for grid problems.
- Truth Tables — The Complete Reference — A truth table shows all possible results. For AND: T&&T=T, T&&F=F, F&&T=F, F&&F=F. For OR: T||T=T, T||F=T, F||T=T, F||F=F. For NOT: !T=F, !F=T. Once you memorize these, logical operators become second nature. Think of AND as strict (both must agree) and OR as lenient (one is enough).
Code example
#include <bits/stdc++.h>
using namespace std;
int main() {
int age;
bool hasTicket, isVIP;
cin >> age;
cin >> hasTicket >> isVIP; // 1 for true, 0 for false
// AND: both conditions required
if (age >= 18 && hasTicket) {
cout << "Welcome! You may enter.\n";
}
// OR: either condition is enough
if (hasTicket || isVIP) {
cout << "You have access to the show.\n";
}
// NOT: flip a condition
if (!isVIP) {
cout << "You are not a VIP.\n";
}
// Combined: adults with ticket OR any VIP
if ((age >= 18 && hasTicket) || isVIP) {
cout << "Backstage pass granted!\n";
}
// CP classic: check if number is in range [1, 100]
int n;
cin >> n;
if (n >= 1 && n <= 100) {
cout << "In range\n";
} else {
cout << "Out of range\n";
}
// Short-circuit: safe division check
int divisor;
cin >> divisor;
if (divisor != 0 && 100 / divisor > 10) {
cout << "Big ratio!\n";
}
// Check if a year is a leap year
int year;
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
cout << year << " is a leap year\n";
} else {
cout << year << " is not a leap year\n";
}
return 0;
}Line-by-line walkthrough
- 1. cin >> age; cin >> hasTicket >> isVIP; — we read the age as an integer, then two boolean values (0 or 1) for ticket and VIP status.
- 2. if (age >= 18 && hasTicket) — the && (AND) operator. Both conditions must be true: the person must be 18 or older AND have a ticket. If either is false, the whole condition is false.
- 3. if (hasTicket || isVIP) — the || (OR) operator. At least ONE condition must be true. Having a ticket works, being a VIP works, having both also works. Only fails if you have neither.
- 4. if (!isVIP) — the ! (NOT) operator flips the value. If isVIP is true, !isVIP is false (so the message does not print). If isVIP is false, !isVIP is true (message prints).
- 5. if ((age >= 18 && hasTicket) || isVIP) — we mix AND and OR with parentheses. The parentheses make it clear: (adults with tickets) OR (VIPs of any age). Without parentheses, the meaning could change!
- 6. if (n >= 1 && n <= 100) — the classic range check pattern. n must be at least 1 AND at most 100. This is how you check if a value is within bounds.
- 7. if (divisor != 0 && 100 / divisor > 10) — short-circuit evaluation in action! If divisor IS 0, the left side (divisor != 0) is false, so C++ never evaluates the right side (100/divisor). This prevents a division-by-zero crash!
- 8. if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) — the famous leap year formula. A year is a leap year if it is divisible by 4 but NOT by 100, unless it IS divisible by 400. The parentheses group the conditions perfectly.
Spot the bug
#include <bits/stdc++.h>
using namespace std;
int main() {
int x;
cin >> x;
// Check if x is between 10 and 20
if (10 <= x <= 20) {
cout << "In range\n";
} else {
cout << "Out of range\n";
}
return 0;
}Need a hint?
C++ does not understand math-style chained comparisons like 10 <= x <= 20. What does C++ actually do with this expression? Think about what (10 <= x) evaluates to, and then what THAT result <= 20 means.
Show answer
The bug is that '10 <= x <= 20' does NOT work like math! C++ evaluates it left to right: first (10 <= x) gives true (1) or false (0), then it compares THAT 0 or 1 with 20. Since 0 <= 20 and 1 <= 20 are both true, this condition is ALWAYS true for any x! The fix: use '(x >= 10 && x <= 20)' — two separate comparisons joined with AND.
Explain like I'm 5
Imagine you want cookies from the cookie jar. Mom says: 'You can have a cookie IF you ate your vegetables AND finished your homework.' That is the AND rule — you need BOTH! But Dad says: 'You can have a cookie IF you ate your vegetables OR cleaned your room.' That is the OR rule — either one works! And NOT is like when someone says 'Do NOT touch the jar' — it flips the rule to the opposite.
Fun fact
George Boole, a self-taught English mathematician from the 1800s, invented the logic system that AND, OR, and NOT are based on. He called it 'Boolean algebra.' He had no idea that 100 years later, his math would become the foundation of EVERY computer chip ever made! Every transistor in your computer is basically doing AND, OR, and NOT operations billions of times per second. The 'bool' data type in C++ is named after him!
Hands-on challenge
Write a leap year checker! A year is a leap year if: (divisible by 4 AND NOT divisible by 100) OR (divisible by 400). Read a year and print 'Leap' or 'Not Leap'. Test: 2024 (Leap), 1900 (Not Leap), 2000 (Leap), 2023 (Not Leap).
More resources
- Codeforces — Beautiful Matrix (Codeforces)
- Logical Operators in C++ — Full Guide (YouTube)
- CP-Algorithms — Boolean Logic Basics (CP-Algorithms)