Systematic Learning of C Language Without Textbooks: 05 In-Depth Study of Relational and Logical Operations

<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

<span>></span>

Greater than

<span>5 > 3</span>

1

<span><</span>

Less than

<span>5 < 3</span>

0

<span>>=</span>

Greater than or equal to

<span>5 >= 5</span>

1

<span><=</span>

Less than or equal to

<span>5 <= 3</span>

0

<span>==</span>

Equal to

<span>5 == 3</span>

0

<span>!=</span>

Not equal to

<span>5 != 3</span>

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

<span>&&</span>

Logical AND

True if both are true

<span>(a>0) && (b<10)</span>

||

Logical OR

True if at least one is true

(a > 0) || (b < 10)

<span>!</span>

Logical NOT

Negation

<span>!(a==b)</span>

Common Mistakes Reminder

Common Priority Errors:

int a = 5, b = 3, c = 2; // Misunderstanding: calculate b&amp;&amp;c first, then compare with a if (a &gt; b &amp;&amp; c) { ... }  // Actual calculation: (a &gt; b) &amp;&amp; c
// Correct way: use parentheses to clarify priority if ((a &gt; b) &amp;&amp; (a &gt; 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 &lt;stdio.h&gt;int main() {    int score;    printf("Please enter your score: ");    scanf("%d", &amp;score);    if (score &gt;= 90) {        printf("Excellent\n");    } else if (score &gt;= 80) {        printf("Good\n");    } else if (score &gt;= 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 &amp;&& year % 100 != 0) || (year % 400 == 0);}
// Determine triangle type void triangle_type(int a, int b, int c) {    if (a + b &gt; c &amp;&& a + c &gt; b &amp;&& b + c &gt; a) {        if (a == b &amp;&& 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 &lt;stdio.h&gt;int main() {    int a = 0, b = 10;    // Example 1: Short-circuit of &amp;&&    if (a != 0 &amp;&& b / a &gt; 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 &gt; 0 || y++ &gt; 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 &lt;stdio.h&gt;int main() {    int year;    scanf("%d", &amp;year);    // Optimize judgment using short-circuit evaluation    int is_leap = (year % 400 == 0) || (year % 4 == 0 &amp;&& year % 100 != 0);    printf("%d\n", is_leap);    return 0;}

Task 2: Luogu P5716 – Month Days Judgment

#include &lt;stdio.h&gt;int main() {    int year, month;    scanf("%d %d", &amp;year, &amp;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 &amp;&& 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 &gt; 3) &amp;&& (b++ &gt; 0);  // a=?, b=?, result1=? // Practice 2  int result2 = (b == 0) || (c / b &gt; 2);  // Is it safe? result2=? // Practice 3 int result3 = !(a &lt; 10) || (c &gt; 5 &amp;&& b == 0);  // result3=?


Homework

Basic Questions (Required) – Online Assessment Questions

  1. Luogu P5711: Leap Year Judgment – Practiced, understand the application of short-circuit evaluation

  2. Luogu P5716: Month Days – Practiced, mastered complex conditional judgment

  3. HDOJ 1008: Elevator – Elevator scheduling problem, practice conditional judgment

Advanced Questions (Optional) – Online Assessment Questions

  1. Luogu P1422: Xiaoyu’s Electricity Bill – Piecewise function calculation, practice multi-condition judgment

  2. POJ 1003: Hangover – Mathematical calculation + conditional judgment

  3. HDOJ 2001: Calculate Distance Between Two Points – Distance calculation + format control

Thought Questions

  1. 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 &lt;stdio.h&gt;int main() {    int n, current = 0, next, time = 0;    while (scanf("%d", &amp;n) != EOF &amp;&& n != 0) {        time = 0;        current = 0;        for (int i = 0; i &lt; n; i++) {            scanf("%d", &amp;next);            if (next &gt; 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 &lt;stdio.h&gt;int main() {    int electricity;    double cost;    scanf("%d", &amp;electricity);    if (electricity &lt;= 150) {        cost = electricity * 0.4463;    } else if (electricity &lt;= 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 &lt;stdio.h&gt;#include &lt;math.h&gt;int is_prime(int n) {    if (n &lt;= 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 &lt;= sqrt(n); i += 2) {        if (n % i == 0) return 0;    }    return 1;}int main() {    int num;    printf("Please enter an integer: ");    scanf("%d", &amp;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!

Leave a Comment