๐ C++ Programming Lesson 9: Detailed Explanation of Logical Operators โ Making Conditional Judgments More “Flexible”

๐ Course Navigation
1ใ๐ค What are Logical Operators? (Why do we need logical operators?)2ใ๐ Three Core Logical Operators (&& “and”, || “or”, ! “not”)3ใ๐งช Practical Case: Solving Judgment Problems in Life (From Scenarios to Code)4ใโ ๏ธ Common Pitfalls and Avoidance Techniques (Avoiding errors in judgment logic)5ใ๐ข Next Lesson Preview: Detailed Explanation of For Loops (The “Magic” for Repeating Code)
1. ๐ค What are Logical Operators? โ Why do we need logical operators?
Previously, we learned about if statements and switch-case matching, but many judgments in life require “looking at multiple conditions together”, for example:
- ๐ซ Amusement Park Ticket Discount: “Age less than 12 and height less than 1.4 meters” to qualify for free admission;
- ๐ฌ Movie Seat Selection: “Seats in the middle area or price less than 50 yuan” can be selected;
- โ No Entry: “not meeting the age of 18″ cannot watch R-rated movies.
These judgments of “and”, “or”, “not” cannot be handled by ordinary relational operators (>, <, ==), which is when we need logical operators! They act like a “conditional puzzle tool” that can combine multiple simple conditions, making program judgments more flexible and closer to real life.
2. ๐ Three Core Logical Operators โ Understanding Each One!
Logical operators have three “partners”, each with a clear role. We will learn using “life examples + code rules”:
(1) &&: “and” operator (both conditions must be met)
โจ Life Scenario: To drink milk tea, you need “money in your pocket and the milk tea shop is open”; both conditions are necessary;
๐ Code Rule: conditionA && conditionB, only when both condition A and condition B are true is the entire expression true; if any condition is false, the result is false.
๐ฐ Example: Judging “whether a person is a teenager” (age โฅ 12 and age < 18)
int age = 15;if (age >= 12 && age < 18) { // 15โฅ12 is true, 15<18 is true, so overall is true cout << "You are a teenager!" << endl;}
โ Truth Table (to help you quickly judge the result):
|
Condition A |
Condition B |
Condition A && Condition B |
|
True |
True |
True |
|
True |
False |
False |
|
False |
True |
False |
|
False |
False |
False |
(2) ||: “or” operator (satisfying one is enough)
โจ Life Scenario: Going out on the weekend, “going to the park or going to the movies”; just choosing one is sufficient;
๐ Code Rule: conditionA || conditionB, as long as one of condition A or condition B is true, the entire expression is true; only when both conditions are false is the result false.
๐ฐ Example: Judging “whether a score is special” (score > 95 or score < 50)
int score = 98;if (score > 95 || score < 50) { // 98>95 is true, so overall is true cout << "This score is very special!" << endl;}
โ Truth Table:
|
Condition A |
Condition B |
Condition A || Condition B |
|
True |
True |
True |
|
True |
False |
True |
|
False |
True |
True |
|
False |
False |
False |
(3) !: “not” operator (inverts the condition)
โจ Life Scenario: “Today not raining” is the negation of “it is raining today”;
๐ Code Rule: !conditionA, inverts the original condition result โ if condition A is true, !conditionA is false; if condition A is false, !conditionA is true.
๐ฐ Example: Judging “whether a person is not late” (!late)
bool isLate = false; // false means "not late", true means "late"if (!isLate) { // Negating "not late"? No โ !false is true, so the condition holds cout << "You are not late, great!" << endl;}
โ Truth Table:
|
Condition A |
! Condition A |
|
True |
False |
|
False |
True |
3. ๐งช Practical Case: Solving Judgment Problems in Life
Talking without practice is just empty talk; let’s use two cases to apply logical operators!
Case 1: Amusement Park Ticket Discount Judgment
Requirement: “Age < 12 and height < 1.4 meters” for free admission; “Age โฅ 60 or has a student card” for half price.
#include using namespace std;int main() {int age;double height;bool hasStudentCard; // true=has student card, false=does not have// Input information cout << "Please enter your age:"; cin >> age; cout << "Please enter your height (meters):"; cin >> height; cout << "Do you have a student card? (1=yes, 0=no):"; cin >> hasStudentCard;// Judgment for discountif (age < 12 && height < 1.4) { cout << "Congratulations! You can enter for free!" << endl; } else if (age >= 60 || hasStudentCard) { cout << "You can enjoy a half-price discount!" << endl; } else { cout << "Please purchase a full-price ticket!" << endl; }return 0;}
๐ Running Scenarios:
- Input: Age 10, Height 1.3, Has Student Card (0) โ Output “Free Admission”;
- Input: Age 65, Height 1.7, Has Student Card (0) โ Output “Half Price”;
- Input: Age 15, Height 1.6, Has Student Card (1) โ Output “Half Price”.
Case 2: Password Validity Check
Requirement: Password must be “length โฅ 8 and contains a number (assumed to be represented by hasNum) and is not purely numeric (!isOnlyNum)”.
#include using namespace std;int main() { int passwordLength; bool hasNum, isOnlyNum; cout << "Please enter password length:"; cin >> passwordLength; cout << "Does the password contain numbers? (1=yes, 0=no):"; cin >> hasNum; cout << "Is the password purely numeric? (1=yes, 0=no):"; cin >> isOnlyNum; if (passwordLength >= 8 && hasNum && !isOnlyNum) { cout << "Password is valid and can be used!" << endl; } else { cout << "Password is invalid, please reset it!" << endl; } return 0;}
๐ Running Scenarios:
- Input: Length 10, Contains Number (1), Purely Numeric (0) โ Output “Valid”;
- Input: Length 7, Contains Number (1), Purely Numeric (0) โ Output “Invalid” (length not sufficient).
4. โ ๏ธ Common Pitfalls and Avoidance Techniques
Although logical operators are useful, one can easily make mistakes; these pitfalls must be avoided!
โ Pitfall 1: Confusing the meanings of “&&” and “||”
For example, to judge “age between 10 and 20”, writing it as age > 10 || age < 20 โ this is wrong!
๐ Problem: “Age > 10 or < 20” actually includes all ages (for example, 30 > 10 is satisfied; 5 < 20 is also satisfied), which does not limit at all;
โ Correct: It should be “and” โ age > 10 && age < 20 (only when both ” > 10″ and ” < 20″ are satisfied is it between 10 and 20).
โ Pitfall 2: Forgetting the priority of “!” (and using parentheses)
For example, to judge “not (age < 12 and height < 1.4)”, writing it as !age < 12 && height < 1.4 โ wrong!
๐ Problem: The priority of ! is higher than <, it will first calculate !age (for example, age=10, !10 is 0), then compare with 12, completely deviating from the original meaning;
โ Correct: Add parentheses to clarify the range โ !(age < 12 && height < 1.4) (first calculate the “age < 12 and height < 1.4” in parentheses, then negate).
โ Pitfall 3: Using “&&” to judge “or” requirements
For example, to judge “score is failing (<60) or full score (=100)”, writing it as score < 60 && score == 100 โ wrong!
๐ Problem: A score cannot be “both < 60 and = 100”; this condition is always false;
โ Correct: Use “or” โ score < 60 || score == 100.
5. ๐ข Next Lesson Preview: Detailed Explanation of For Loops (The “Magic” for Repeating Code)
In this lesson, we learned to use logical operators to combine conditions, such as judging ticket discounts and password validity. But if we need to “repeat an action” โ for example, “print ‘I love programming’ 10 times”, “calculate the sum from 1 to 100”, “grade 10 students’ scores”, we can’t just write the same code 10 or 100 times, right?
In the next lesson, we will learn about for loops โ it acts like a “code repeater”; just tell it “how many times to repeat” and “what to do each time”, and it can automatically execute the code block repeatedly! For example, with just 3 lines of code, you can print all numbers from 1 to 100 without writing 100 lines of cout.
For loops are the core of “automating repetitive operations” in programming, such as in games where “enemies appear every 5 seconds” or in calculations where “summing 100 numbers” relies on it. Looking forward to unlocking it together in the next lesson! ๐
