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
In a game, the next level opens when you have at least 100 points and at the same time at least 3 stars. In place of the comment, write an if statement that prints Next level unlocked only if points is at least 100 and stars is at least 3. Join the two comparisons with &&.
Add an else branch that prints You need 100 points and 3 stars. Then change stars to 2. One false part is enough to make the whole condition false, so the program prints You need 100 points and 3 stars.
Start programming for free
7/12