Lesson 2 of 6 · Control Flow · 2 min read · Updated
else if and the ternary operator
Choosing between many ranges with an else-if ladder, and picking a value in one line with ?:.
An if with one else chooses between two paths. When there are more — grades, tax slabs, age groups — chain them with else if. C tests each condition from the top and runs the first one that is true; the rest are skipped.
#include <stdio.h>
int main(void)
{
int marks = 72;
if (marks >= 90) {
printf("Grade A\n");
} else if (marks >= 75) {
printf("Grade B\n");
} else if (marks >= 50) {
printf("Grade C\n");
} else {
printf("Fail\n");
}
return 0;
}
Grade C
Warning
Order matters. Put marks >= 50 first and every pass mark — even 95 — prints "Grade C", because that test is true first and the others are never reached. In a ladder of ranges, test the highest range first.
The ternary operator ?:
#include <stdio.h>
int main(void)
{
int a = 17, b = 42;
int bigger = (a > b) ? a : b;
int n = 7;
printf("bigger: %d\n", bigger);
printf("%d is %s\n", n, (n % 2 == 0) ? "even" : "odd");
return 0;
}
bigger: 42
7 is odd
Read condition ? x : y as "if the condition is true, the value is x, otherwise y". It is an expression — it produces a value — so it fits inside an assignment or a printf, where a whole if statement cannot go.
Note
Use ?: for a simple choice between two values. Nesting one inside another quickly becomes unreadable — at that point an else if ladder is clearer.
int x = 10; int y = (x > 5) ? 1 : 0; — what is y?
Try this now
- Read a temperature and print "Cold" below 20, "Pleasant" up to 30, "Hot" up to 40 and "Very hot" above.
- Read a number and print whether it is positive, negative or zero using an else-if ladder.
- Use a ternary operator to print the smaller of two numbers.
Create a free account to save your progress, or sign in.