90 דק׳

שילוב תנאים: &&, || ו־!

אופרטורים לוגיים וטבלאות אמת, בדיקת טווח עם &&, חלופות עם ||, היפוך עם !, סוגריים, למה 0 <= score <= 100 לא עובד ב־C, והערכה מקוצרת. משימה מסכמת: מנתח מספרים.

למצגתלקריאה באתרבאנגלית בלבד

השיעור הזה כתוב באנגלית בלבד.

Two questions in one condition

Many rules ask two questions at once. A valid score is at least 0 and at most 100. A user who answers Y or y said yes. C joins conditions with three logical operators (אופרטורים לוגיים):

OperatorNameMeaningExample
&&ANDboth conditions must be trueage >= 18 && age <= 65
||ORat least one condition must be truechoice == 'Y' || choice == 'y'
!NOTturns true into false and false into true!(number == 0)

A condition built with them is a compound condition (תנאי מורכב). Like a comparison, a logical operator always gives 1 (true) or 0 (false).

AND: both sides must be true

A && B is true only when A is true and B is true. A truth table (טבלת אמת) lists every combination:

ABA && B
000
010
100
111

Think of two switches in series in front of an LED. A closed switch is a true condition. Current flows, and the LED lights, only when both switches are closed. Use && when every requirement must hold.

Click the switches A and B. The LED, the expression and the row of the truth table follow.לפתיחה במסך מלא

A range check needs two comparisons

"The score is from 0 to 100" is two questions: is it at least 0, and is it at most 100?

score >= 0 && score <= 100
scorescore >= 0score <= 100&&
-1010
55111
101100

Both limits are inside the range because the comparisons use >= and <=.

Each band shows where a comparison is true. AND keeps only the part where both are true: 0 to 100.לפתיחה במסך מלא

OR: one true side is enough

A || B is true when at least one side is true. It is false only when both sides are false:

ABA || B
000
011
101
111

These are two switches in parallel: one closed switch is enough for the LED to light. Use || when any one of the options is enough.

NOT: flip one condition

!A turns 0 into 1 and a true value into 0:

A!A
01
10

!(score >= 55) means "score is not at least 55". With a score of 40: !(40 >= 55) becomes !0, which is 1. When a simpler comparison says the same thing, prefer it: score < 55 is easier to read.

Parentheses show the groups

Tom's example: is_weekend holds 1 on Saturday and Sunday and 0 on other days. The rule is "it is the weekend, and the hour is before 8 or from 18 on":

is_weekend && (hour < 8 || hour >= 18)

With is_weekend = 1 and hour = 20, work it out in three steps:

  1. Each comparison: 1 && (0 || 1)
  2. The parentheses, the ||: 1 && 1
  3. The &&: 1

Course rule: use parentheses to show the groups you mean. Then nobody, including you, has to remember which operator C works out first.

C does not read 0 <= score <= 100 like maths

In maths, 0≤score≤1000 \le score \le 100 is a range. In C it compiles, but it means something else. C works left to right: first 0 <= score gives 0 or 1, and then that 0 or 1 is compared with 100.

With a score of 150: (0 <= 150) <= 100 becomes 1 <= 100, which is 1. So 150 is accepted. In fact every score is accepted, because both 0 and 1 are at most 100.

Turn the range into two C questions joined by AND: score >= 0 && score <= 100. With 150 that gives 1 && 0, which is 0.

Enrichment: short circuit

C works out && and || from left to right, and stops as soon as the answer is known. This is called short-circuit evaluation (הערכה מקוצרת).

if (divisor != 0 && number / divisor > 5)
{
    printf("Large quotient\n");
}

When divisor is 0, the left side 0 != 0 is 0. A false left side makes the whole && false, so the right side never runs, and there is no division by zero. Put the safety check on the left of &&. The same idea works for ||: a true left side makes the whole || true.

Worked program: is the score valid?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int score;
    scanf("%d", &score);
    if (score >= 0 && score <= 100)
    {
        printf("Valid score\n");
    }
    else
    {
        printf("Invalid score\n");
    }
    return 0;
}
100
Valid score

The tests -1, 0, 100 and 101 check both boundaries: below and at 0, at and above 100.

Step through with 100, then click -1, 0 and 101. With -1 the left side is already 0, so the right side is not checked.לפתיחה במסך מלא

Debugging: every input is valid

This program reports every integer as valid:

if (score >= 0 || score <= 100)
{
    printf("Valid\n");
}
else
{
    printf("Invalid\n");
}

Test -10: the left side is 0, but the right side -10 <= 100 is 1. Test 150: the right side is 0, but the left side is 1. With || one true side is enough, and every number passes at least one side. A range needs both limits to hold, so the repair is &&.

With || the result band covers the whole number line: there is no value that gives Invalid.לפתיחה במסך מלא

Task: a number analyzer

The program is finished when all six acceptance tests match:

InputSignParityRange
-11NegativeOddOut of range
-10NegativeEvenIn range
-1NegativeOddIn range
0ZeroEvenIn range
10PositiveEvenIn range
11PositiveOddOut of range

Each test checks a boundary, a category, or both.

Answer

נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.

    Key words

    EnglishHebrewMeaning
    logical operatorאופרטור לוגי&&, || or !
    compound conditionתנאי מורכבconditions joined by && or ||
    AND &&וגםtrue only when both sides are true
    OR ||אוtrue when at least one side is true
    NOT !לא (שלילה)flips 0 and 1
    truth tableטבלת אמתevery combination of inputs and its result
    rangeטווחthe values between two limits
    short circuitהערכה מקוצרתstop as soon as the answer is known

    Practice

    All of Tom's questions for this lesson, with answers, are on the practice page (questions 21 to 26 and 29 to 32).