<In-Depth Study of Relational and Logical Operations>From novice to expert, from Hello World to ACMFull of practical content, no textbooks required!
Relational and logical operations are the foundation for programs to make “intelligent judgments”.
1. Relational Expressions and Logical Expressions
Review and In-Depth Understanding of Relational Operators
Relational operators are used to compare the size relationship between two values, resulting in<span>true (1)</span> or <span>false (0)</span>:
|
Operator |
Meaning |
Example |
Result |
|---|---|---|---|
|
|
Greater than |
|
1 |
|
|
Less than |
|
0 |
|
|
Greater than or equal to |
|
1 |
|
|
Less than or equal to |
|
0 |
|
|
Equal to |
|
0 |
|
|
Not equal to |
|
1 |
In-Depth Understanding of Logical Operators
Logical operators are used to combine multiple conditions to construct complex judgment logic:
|
Operator |
Meaning |
Truth Table |
Example |
|---|---|---|---|
|
|
Logical AND |
True if both are true |
|
|
|| |
Logical OR |
True if at least one is true |
|
|
|
Logical NOT |
Negation |
|
Common Mistakes Reminder
Common Priority Errors:
int a = 5, b = 3, c = 2; // Misunderstanding: calculate b&&c first, then compare with a if (a > b && c) { ... } // Actual calculation: (a > b) && c
// Correct way: use parentheses to clarify priority if ((a > b) && (a > c)) { ... }
2. Conditional Judgments and Program Flow Control
Basic Structure of Conditional Judgments
Conditional judgments allow the program to execute different code branches based on different situations:
#include <stdio.h>int main() { int score; printf("Please enter your score: "); scanf("%d", &score); if (score >= 90) { printf("Excellent\n"); } else if (score >= 80) { printf("Good\n"); } else if (score >= 60) { printf("Pass\n"); } else { printf("Fail\n"); } return 0;}
Complex Conditional Judgment Example
// Determine if a year is a leap year int is_leap_year(int year) { // Divisible by 4 but not by 100, or divisible by 400 return (year % 4 == 0 &&& year % 100 != 0) || (year % 400 == 0);}
// Determine triangle type void triangle_type(int a, int b, int c) { if (a + b > c &&& a + c > b &&& b + c > a) { if (a == b &&& b == c) { printf("Equilateral triangle\n"); } else if (a == b || a == c || b == c) { printf("Isosceles triangle\n"); } else if (a*a + b*b == c*c || a*a + c*c == b*b || b*b + c*c == a*a) { printf("Right triangle\n"); } else { printf("Ordinary triangle\n"); } } else { printf("Cannot form a triangle\n"); }}
3. Short-Circuit Evaluation Principles and Applications
Short-Circuit Evaluation Principles
Short-circuit evaluation is an important feature of C language that can improve program efficiency:
<span>&&</span> Short-circuit: If the first expression is false, the second expression is not evaluated
<span>||</span> Short-circuit: If the first expression is true, the second expression is not evaluated
Short-Circuit Evaluation Application Example
#include <stdio.h>int main() { int a = 0, b = 10; // Example 1: Short-circuit of &&& if (a != 0 &&& b / a > 2) { // Both sides are wrong, but the program will not cause a division by zero error. // Because a!=0 is false, the if statement will not enter the compound statement printf("Condition met\n"); } else { printf("Condition not met, but avoided division by zero error\n"); } // Example 2: Short-circuit of || int x = 5, y = 0; if (x > 0 || y++ > 0) { // The latter y++ is false, but y++ will not execute because x>0 is true // After determining the former is true, directly enter the compound statement without executing the latter printf("x=%d, y=%d\n", x, y); // Output: x=5, y=0 } return 0;}
Common Questions and Answers
Q: When should short-circuit evaluation be used?
A: When the second expression has a high computation cost or may have side effects, such as checking for null pointers, array out-of-bounds checks, etc.
Q: Will short-circuit evaluation affect program logic?
A: It will not affect the logical result, but it may affect the execution of expressions with side effects.
In-Class Test
Practical Exercise Guidance
Task 1: Luogu P5711 – Leap Year Judgment
#include <stdio.h>int main() { int year; scanf("%d", &year); // Optimize judgment using short-circuit evaluation int is_leap = (year % 400 == 0) || (year % 4 == 0 &&& year % 100 != 0); printf("%d\n", is_leap); return 0;}
Task 2: Luogu P5716 – Month Days Judgment
#include <stdio.h>int main() { int year, month; scanf("%d %d", &year, &month); int days; if (month == 2) { // Determine leap year: divisible by 400, or divisible by 4 but not by 100 int is_leap = (year % 400 == 0) || (year % 4 == 0 &&& year % 100 != 0); days = is_leap ? 29 : 28; } else if (month == 4 || month == 6 || month == 9 || month == 11) { days = 30; } else { days = 31; } printf("%d\n", days); return 0;}
Expression Evaluation Practice
Analyze the value and execution process of the following expressions:
int a = 5, b = 0, c = 10; // Practice 1 int result1 = (a > 3) &&& (b++ > 0); // a=?, b=?, result1=? // Practice 2 int result2 = (b == 0) || (c / b > 2); // Is it safe? result2=? // Practice 3 int result3 = !(a < 10) || (c > 5 &&& b == 0); // result3=?
Homework
Basic Questions (Required) – Online Assessment Questions
-
Luogu P5711: Leap Year Judgment – Practiced, understand the application of short-circuit evaluation
-
Luogu P5716: Month Days – Practiced, mastered complex conditional judgment
-
HDOJ 1008: Elevator – Elevator scheduling problem, practice conditional judgment
Advanced Questions (Optional) – Online Assessment Questions
-
Luogu P1422: Xiaoyu’s Electricity Bill – Piecewise function calculation, practice multi-condition judgment
-
POJ 1003: Hangover – Mathematical calculation + conditional judgment
-
HDOJ 2001: Calculate Distance Between Two Points – Distance calculation + format control
Thought Questions
-
Write a program to determine if a number is prime (a prime number), using short-circuit evaluation to optimize the judgment process
Homework Answers
HDOJ 1008: Elevator Answer
#include <stdio.h>int main() { int n, current = 0, next, time = 0; while (scanf("%d", &n) != EOF &&& n != 0) { time = 0; current = 0; for (int i = 0; i < n; i++) { scanf("%d", &next); if (next > current) { time += (next - current) * 6; } else { time += (current - next) * 4; } time += 5; // Stop time current = next; } printf("%d\n", time); } return 0;}
Luogu P1422: Xiaoyu’s Electricity Bill Answer
#include <stdio.h>int main() { int electricity; double cost; scanf("%d", &electricity); if (electricity <= 150) { cost = electricity * 0.4463; } else if (electricity <= 400) { cost = 150 * 0.4463 + (electricity - 150) * 0.4663; } else { cost = 150 * 0.4463 + 250 * 0.4663 + (electricity - 400) * 0.5663; } printf("%.1f\n", cost); return 0;}
Thought Question Answer: Optimized Prime Judgment
#include <stdio.h>#include <math.h>int is_prime(int n) { if (n <= 1) return 0; if (n == 2) return 1; if (n % 2 == 0) return 0; // Optimize using short-circuit evaluation: only check up to sqrt(n) for (int i = 3; i <= sqrt(n); i += 2) { if (n % i == 0) return 0; } return 1;}int main() { int num; printf("Please enter an integer: "); scanf("%d", &num); if (is_prime(num)) { printf("%d is prime\n", num); } else { printf("%d is not prime\n", num); } return 0;}
In the next class, we will learn:
Selection Structure Program Design
Remember to practice the questions on the online assessment platform, as they are excellent practical training!
The author has something to say:
If you can persist in learning to this point, it at least shows that you are a person who can persevere.
I want to remind you of one thing:
From the beginning, all the code in the course and basic exercises are carefully selected problems that beginners must master.
You must personally, independently, and without looking at the answers type it out,
because the difference between “I thought I understood” and “I really understand” is extremely significant in programming learning.
Rest assured, if the questions are really easy for you, they won’t waste much of your time.
If you have questions, feel free to chat in the comments!
Follow YunJie Algorithm, no textbooks needed, just a finger tap to systematically learn programming!