C If ... Else
A program becomes useful when it can choose what to do. The if statement runs a block of code only when a condition is true.
if
#include <stdio.h>
int main(void) {
int temperature = 31;
if (temperature > 30) {
printf("It is hot today.\n");
}
printf("Done.\n");
return 0;
}It is hot today. Done.
The condition goes in brackets; the code to run goes in curly braces. Braces are optional for a single statement, but always writing them avoids a classic bug when a second line is added later.
else
else runs when the condition is false, so exactly one of the two blocks runs.
#include <stdio.h>
int main(void) {
int number = 7;
if (number % 2 == 0) {
printf("%d is even\n", number);
} else {
printf("%d is odd\n", number);
}
return 0;
}7 is odd
else if
To choose between more than two cases, chain tests with else if. They are checked from the top, and the first true one wins; the rest are skipped.
#include <stdio.h>
int main(void) {
int marks;
printf("Marks (0-100): ");
scanf("%d", &marks);
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("Grade D\n");
}
return 0;
}78
Marks (0-100): Grade B
The order matters: if the test for marks >= 50 came first, a mark of 95 would get a C. Run the example and type different marks to see each branch.
Combining conditions
Use && (and), || (or) and ! (not) to combine conditions: if (age >= 13 && age <= 19) is true for teenagers. Use brackets when you mix && and || so the meaning is clear.
A common mistake: = instead of ==
if (x = 5) does not compare: it stores 5 in x, and since 5 is not zero, the condition is always true. Always use == to compare. With -Wall, the compiler warns about this mistake.
The conditional operator
For a choice between two values, there is a short form: condition ? valueIfTrue : valueIfFalse.
#include <stdio.h>
int main(void) {
int a = 12, b = 30;
int bigger = (a > b) ? a : b;
printf("The bigger number is %d\n", bigger);
printf("%s\n", bigger > 20 ? "large" : "small");
return 0;
}The bigger number is 30 large
Use it for short choices only; for anything longer, if and else are easier to read.
Practice exercises
- Read a year and print whether it is a leap year: divisible by 4, but not by 100 unless also by 400. Test 2000, 1900 and 2024.
- Read three numbers and print the largest.
- Read a temperature and print "cold" below 15, "pleasant" from 15 to 30 and "hot" above 30.