← Back to C Course | Chapter 4: Control Flow | Lesson 3 of 11

C else-if Ladder

What is an else-if Ladder?

An else-if ladder chains multiple conditions together so they're checked in order, and as soon as one evaluates to true, its block runs and every later condition in the chain is skipped without being checked at all.

Example: What is an else-if Ladder?

c
#include <stdio.h>
int main() {
	int score = 75;
	if (score >= 90) {
		printf("A");
	} else if (score >= 70) {
		printf("B");
	} else {
		printf("C");
	}
	return 0;
}

Grading System

Assigning letter grades based on numeric score ranges is a textbook use of an else-if ladder -- each condition tests a lower boundary, and because they're checked in order, only the first matching range applies.

Example: Grading System

c
#include <stdio.h>
int main() {
	int score = 82;
	if (score >= 90) {
		printf("A");
	} else if (score >= 80) {
		printf("B");
	} else if (score >= 70) {
		printf("C");
	} else {
		printf("F");
	}
	return 0;
}

Number Classification

You can classify a number as positive, negative, or zero with three chained conditions in an else-if ladder, which reads far more clearly than three separate, unrelated if statements checking the same variable.

Example: Number Classification

c
#include <stdio.h>
int main() {
	int n = -5;
	if (n > 0) {
		printf("Positive");
	} else if (n < 0) {
		printf("Negative");
	} else {
		printf("Zero");
	}
	return 0;
}

Age Categories

Grouping ages into categories like child, adult, and senior with an else-if ladder keeps the boundaries between categories explicit and easy to adjust later, since each range is defined in one place.

Example: Age Categories

c
#include <stdio.h>
int main() {
	int age = 45;
	if (age < 13) {
		printf("Child");
	} else if (age < 65) {
		printf("Adult");
	} else {
		printf("Senior");
	}
	return 0;
}

Temperature Guides

Classifying temperature ranges (cold, mild, hot) is a natural fit for an else-if ladder, since each condition only needs to check one boundary given that earlier, more extreme ranges have already been ruled out by prior checks.

Example: Temperature Guides

c
#include <stdio.h>
int main() {
	int temp = 85;
	if (temp < 50) {
		printf("Cold");
	} else if (temp < 80) {
		printf("Mild");
	} else {
		printf("Hot");
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.