Codiqo

Learn C · lesson 14 of 60 · about 8 minutes

else if and Nesting

Check the CPU temperature: choose between several outcomes with else if, catch impossible values first, and put decisions inside decisions.

What you'll learn

  • Chain conditions with else if
  • Order conditions correctly
  • Nest an if inside another

More than two outcomes

The report should say how hot the CPU is: 85 or more is too hot, 60 or more is warm, and anything lower is cool. That's three outcomes, and if with else only gives two.

else if adds more conditions. They're checked from the top, only the first true branch runs, and else catches whatever is left.

Sorting a temperature

#include <stdio.h>

int main(void) {
    int temp = 70;
    if (temp >= 85) {
        printf("CPU too hot!\n");
    } else if (temp >= 60) {
        printf("CPU warm\n");
    } else {
        printf("CPU cool\n");
    }
    return 0;
}

Output

CPU warm

Order matters

Check in one direction. Here that's the hottest band first: if temp >= 60 came first, 95 would match it and the report would only say warm. And check impossible values before anything else: a reading below 0 or above 120 means the sensor is broken, so temp < 0 || temp > 120 goes at the top.

Nested checks

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    bool loggedIn = true;
    bool isPlus = false;
    if (loggedIn) {
        if (isPlus) {
            printf("Unlimited fuel\n");
        } else {
            printf("Fuel: 5\n");
        }
    } else {
        printf("Please sign in\n");
    }
    return 0;
}

Output

Fuel: 5

Tip

C has no elif: it's two words, else if.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.