Logical Operators: or
The second logical operator is || (two vertical bars in a row), which means “or”. Say the days of the week are numbered from 1 (Monday) to 7 (Sunday). “If it's day 6 or day 7, it's the weekend”:
int day = 7;
if (day == 6 || day == 7) {
printf("It's the weekend\n");
}This prints:
It's the weekendA condition joined with || is true if at least one of its parts is true. It's false only if all of them are false:
true || trueistruetrue || falseistruefalse || trueistruefalse || falseisfalse
A common mistake is to shorten the condition the way we speak: day == 6 || 7. The right part is then just the number 7, not a comparison. And as you know from the exercise on true and false, any number other than 0 counts as true. So the whole condition is always true, even on a Monday, and the compiler doesn't report any error. Each part needs its own comparison: day == 6 || day == 7.
You can use && and || in one condition. Just as multiplication goes before addition, && goes before ||. Group what belongs together with parentheses, just like in math:
int day = 6;
int temperature = 15;
if ((day == 6 || day == 7) && temperature > 20) {
printf("We're going on a trip\n");
} else {
printf("We're staying home\n");
}This prints:
We're staying homeThe part in parentheses is evaluated first: it's Saturday, so it's true. But temperature > 20 is false, and true && false is false. Without the inner parentheses, the program would first join day == 7 && temperature > 20, and the condition would be true every Saturday, whatever the weather. The outer parentheses belong to the if statement, which is why there are two at the start of the condition.
Instructions
A cinema gives a discount to students and to people aged 65 or more. In place of the comment, write an if statement that prints Discount if is_student is true or age is at least 65. Use ||.
New rule: discounts are only on Wednesdays, that is, when day is 3. Add && day == 3 at the end of the condition, put the part with || in parentheses, and add an else branch that prints Full price. Today is Monday (day is 1), so the program prints Full price.
Start programming for free
8/12