Skip to content
FollowtheDamnCode

else if

Choosing between many options.

4 minute read

Big idea

else if chains conditions together so you can pick one of many options.

The idea

if (score >= 90) {
    printf("A\n");
} else if (score >= 80) {
    printf("B\n");
} else if (score >= 70) {
    printf("C\n");
} else {
    printf("Keep practising\n");
}

C checks each condition from the top, in order, and runs the first one that's true. Everything after that is skipped — even if it would also be true.

That's why score >= 80 doesn't need to say "and less than 90": if the score were 90 or more, the first branch would already have run.

Grade a score — change it and rerun
#include <stdio.h>

int main(void) {
    int score = 84;
    if (score >= 90) {
        printf("A\n");
    } else if (score >= 80) {
        printf("B\n");
    } else if (score >= 70) {
        printf("C\n");
    } else {
        printf("Keep practising\n");
    }
    return 0;
}
output
B

Run and edit it in the app.

Order matters

Put the most specific condition first. Watch what happens when the order is wrong:

Fix the bug: 95 should be an A
#include <stdio.h>

int main(void) {
    int score = 95;
    if (score >= 70) {
        printf("C\n");
    } else if (score >= 80) {
        printf("B\n");
    } else if (score >= 90) {
        printf("A\n");
    }
    return 0;
}
output
A

Run and edit it in the app.

95 is >= 70, so the first branch wins and the rest never get a look.

With the chain if (n > 0) … else if (n > 10) … else … what runs for n = 50?

Watch it

Think of it like

A lift that stops at the first floor whose button is lit, starting from the top. It doesn't visit every lit floor — just the first one it reaches.

🕷️ Spidey-sense: Threat triage: if it's a bank robbery, go. Else if it's a cat in a tree, go after. Else, patrol. First match wins — I can't be in two places at once.

Key terms

  • else if — A condition checked only when every condition above it was false.
  • Chain — A sequence of if / else if / else; exactly one branch runs (or none, without a final else).

Check yourself

In an if / else if chain, how many branches run?

For a grade chain, which condition should come first?

When does a final else run?