C course menu
if, else if and else in C: Conditions, Nested if and the Ternary Operator
Learn conditional statements in C: if, if-else and else-if chains, conditions that are true when non-zero, combining conditions with && and ||, nested if and the dangling else, the ternary operator, and common mistakes such as = instead of ==.
On this page
The if statement runs code only when a condition is true. In C, "true" means any non-zero value, and "false" means zero.
if#
int temperature = 34;
if (temperature > 30) {
printf("It's hot. Drink water!\n");
}
printf("Have a nice day.\n");It's hot. Drink water!
Have a nice day.if-else#
int balance = 250, price = 400;
if (balance >= price) {
printf("Payment successful\n");
} else {
printf("You need %d more\n", price - balance);
}You need 150 moreelse if chains#
Conditions are checked from top to bottom; only the first true branch runs:
#include <stdio.h>
char grade(int marks) {
if (marks >= 90) {
return 'A';
} else if (marks >= 75) {
return 'B';
} else if (marks >= 50) {
return 'C';
} else {
return 'F';
}
}
int main(void) {
printf("%c %c %c %c\n", grade(95), grade(80), grade(62), grade(30));
return 0;
}A B C FOrder matters: with marks >= 50 first, 95 would get a C.
Combining conditions#
int age = 25, has_licence = 1, is_weekend = 0;
if (age >= 18 && has_licence) {
printf("Can rent a car\n");
}
if (is_weekend || age < 12) {
printf("Discount\n");
} else {
printf("Full price\n");
}Can rent a car
Full priceNon-zero is true#
Any value can be used as a condition:
int items = 0;
if (items) {
printf("Cart has items\n");
} else {
printf("Cart is empty\n");
}
if (!items) {
printf("Still empty\n");
}Cart is empty
Still emptyFor pointers, if (ptr) means "the pointer is not NULL" (Pointers).
Nested if and the dangling else#
An else belongs to the nearest if that does not already have one, whatever the indentation suggests:
int x = 5, y = -1;
if (x > 0)
if (y > 0)
printf("both positive\n");
else
printf("this else belongs to 'if (y > 0)'\n");this else belongs to 'if (y > 0)'Always use braces to make the structure explicit; GCC warns about this case with -Wall.
The ternary operator#
condition ? a : b chooses between two values:
int n = 7;
printf("%d is %s\n", n, n % 2 == 0 ? "even" : "odd");7 is oddCommon mistakes#
Practice#
Practice exercise
Write a function int is_leap(int year) that returns 1 for leap years (divisible by 4, except centuries, unless divisible by 400) and test it with 2024, 1900, 2000 and 2026.
Show solution
#include <stdio.h>
int is_leap(int year) {
if (year % 400 == 0) return 1;
if (year % 100 == 0) return 0;
return year % 4 == 0;
}
int main(void) {
int years[] = {2024, 1900, 2000, 2026};
for (int i = 0; i < 4; i++) {
printf("%d: %s\n", years[i], is_leap(years[i]) ? "leap" : "not leap");
}
return 0;
}2024: leap
1900: not leap
2000: leap
2026: not leapKey takeaway#
Finished this lesson?