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

The else Branch

The if statement runs its block only if the condition is true. Often, though, you want to do something when it isn't true, too. That's what else is for:

int temperature = 12;

if (temperature > 25) {
    printf("Take a cap\n");
} else {
    printf("Take a jacket\n");
}

This prints:

Take a jacket

The condition temperature > 25 is false, so the program skips the first block and runs the block after else. These two blocks are called branches: like a road that forks, the program always takes exactly one of them. If the condition is true, the first branch, otherwise the second. It never runs both, and it never skips both.

You write else right after the closing brace of the if block, usually on the same line: } else {. There must be no other statement between the } and the else. Otherwise the else has nothing to belong to, and the compiler reports error: expected expression.

else has no condition of its own: it gets all the cases the if didn't cover. If you give it one anyway, for example } else (temperature <= 25) {, the compiler reports error: expected ';' after expression. The error suggests adding a semicolon, but the right fix is to delete the condition after else.

Instructions

  1. 1

    The monitor now costs 5000, so the program prints nothing. Add an else branch to the if statement that prints I won't buy the monitor.

  2. 2

    Change monitor_price to 3500 and run the program again. Now the condition is true, so the program takes the first branch and prints only I'll buy the monitor.

Back

3/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.