CodeBlanks Logo Icon CodeBlanks

else and else if

Learn else and else if chains for alternative cases.

else and else if

else adds a block that runs when an if condition is false. With else if you chain another condition to check.

int score = 75;
if (score >= 85) {
    printf("Excellent\n");
} else if (score >= 70) {
    printf("Good\n");
} else {
    printf("Pass\n");
}

Order matters: the first true condition's block runs, the rest is skipped. If none is true, the else block runs. Here 75 >= 85 is false, 75 >= 70 is true; the output is Good.

Logical operators

To combine several conditions in a single if, use && (and), || (or) and ! (not).

int age = 20;
int has_id = 1;
if (age >= 18 && has_id) {
    printf("Allowed\n");
}

&& is true when both sides are true. || is true when at least one side is true. ! flips true to false. With these you can write complex conditions in a clean way.

Practice Letter grades

Write a C program. Declare int score = 75;. Use if, else if and else to print the letter grade: printf("A\n"); if score >= 85, printf("B\n"); if score >= 70, otherwise printf("C\n");. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare score, print letter grade with if/else if/else
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int score = 75;
    if (score >= 85) {
        printf("A\n");
    } else if (score >= 70) {
        printf("B\n");
    } else {
        printf("C\n");
    }
    return 0;
}

Expected output

B

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the else if chain

Question
if (score >= 85) {
    printf("A");
} ____ (score >= 70) {
    printf("Good");
}
Answer
if (score >= 85) {
    printf("A");
} else if (score >= 70) {
    printf("Good");
}

Explanation: else if checks the second condition.

2 For score=75 which block runs?

main.c
if (score >= 85) { A }
else if (score >= 70) { B }
else { C }
  • Block A
  • Block B Correct answer
  • Block C
  • All three

Explanation: 75 >= 85 is false, 75 >= 70 is true; B runs.

3 Match the logical operators

Term Meaning
&& And
|| Or
! Not
else Otherwise

All lessons in Beginner