Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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 && true is true
  • true && false is false
  • false && true is false
  • false && false is false

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. 1

    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 &&.

  2. 2

    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.

Back

8/13

  1. 1. The if Statement
  2. 2. Blocks and Indentation
  3. 3. The else Branch
  4. 4. Comparison Operators
  5. 5. True and False
  6. 6. More Options: else if
  7. 7. Quiz: else if
  8. 8. Logical Operators: and
  9. 9. Logical Operators: or
  10. 10. Logical Operators: not
  11. 11. Nested Conditions
  12. 12. The switch Statement
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.