More Options: else if

With if and else, a program chooses between two options. Often there are more. A football match, for example, ends in one of three ways: the home team wins, the away team wins, or it's a draw. For more options, add else if branches, each with a condition of its own:

int home_goals = 3;
int away_goals = 2;

if (home_goals > away_goals) {
    printf("The home team won!\n");
} else if (home_goals < away_goals) {
    printf("The away team won!\n");
} else {
    printf("It's a draw!\n");
}

This prints:

The home team won!

The program checks the conditions from top to bottom and runs the block of the first true one. It skips the rest of the branches, even if some of the later conditions are true too. Only if no condition is true does the else block run. You can add as many else if branches as you need, always between the if and the else. The else at the end is optional: without it, nothing runs when no condition is true.

Since the first true condition wins, the order of the conditions matters:

int points = 95;

if (points >= 50) {
    printf("Passed\n");
} else if (points >= 90) {
    printf("Excellent\n");
}

This prints:

Passed

95 points is an excellent result, but the first condition, points >= 50, is already true, so the program never gets to the second one. The branch that prints Excellent never runs here, because every number that is at least 90 is also at least 50. Put the stricter condition first: points >= 90, then points >= 50.

Instructions

15 °C isn't weather for a winter coat. Between the if block and else, add an else if branch with the condition temperature > 10 that prints Wear a jacket.

Add one more else if branch with the condition temperature > 18 that prints Wear a sweater, and change temperature to 20. The program should print Wear a sweater. If it prints Wear a jacket, the condition temperature > 10 comes first and catches 20 degrees too: move the new branch above it.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/12