Learn

We can also add an else clause to an if statement to provide code that will only be executed if the initial if condition is false. Here’s a form of an if statement that includes an else clause:

if (condition) { // Statement1 — do something } else { // Statement2 — do something else }
  • If condition is true, statement1 is executed. Then the program skips statement2 and executes any code statements following the if / else clause.
  • If condition is false, statement1 is skipped and statement2 is executed. After statement2 completes, the program executes any code statements following the if / else clause.
if (coin == 1) { printf("Heads\n"); } else { printf("Tails\n"); }

In the code above, if coin is equal to 1, the program outputs “Heads”; if it does not, then it outputs “Tails.”

Note: It’s either or — only one of them will execute!

Instructions

1.

Add an else statement that prints “Fail\n”.

2.

Add a second if / else statement with the condition grade2 > 60 that prints “Pass\n” if true and “Fail\n” if otherwise. Run the program again to see how the else clause gets skipped when the condition isn’t false!

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?