Logical Operators: and
Sometimes one condition isn't enough. “I'll buy the sneakers if they cost less than 2000 and they're my size” is made of two conditions joined by the word “and”. In C, that's the operator && (two & characters in a row). Read it as “and”:
int price = 1800;
int size = 42;
if (price < 2000 && size == 42) {
printf("I'll buy the sneakers\n");
}This prints:
I'll buy the sneakers&& is a logical operator: it joins two conditions into one. The joined condition is true only if both parts are true. If even one of them is false, the whole condition is false:
true && trueistruetrue && falseisfalsefalse && trueisfalsefalse && falseisfalse
You can join more conditions in a row: a && b && c is true only if all three are true.
Each part must be a complete comparison. “Age from 13 to 19” is age >= 13 && age <= 19. If you shorten it the way we speak, to age >= 13 && <= 19, the compiler reports error: expected expression, because it doesn't know what <= 19 should compare. The math notation 13 <= age <= 19 doesn't work either. For that one, the compiler reports error: chained comparison 'X <= Y <= Z' does not behave the same as a mathematical expression: chaining comparisons like this doesn't mean in C what it means in math.
Instructions
- 1
In a game, the next level opens when you have at least
100points and at the same time at least3stars. In place of the comment, write anifstatement that printsNext level unlockedonly ifpointsis at least 100 andstarsis at least 3. Join the two comparisons with&&. - 2
Add an
elsebranch that printsYou need 100 points and 3 stars. Then changestarsto2. One false part is enough to make the whole condition false, so the program printsYou need 100 points and 3 stars.