if and else
Do one thing or another.
4 minute read
Big idea
if runs a block of code only when a condition is true. else runs when it isn't.
The idea
if (condition) {
// runs when condition is true
} else {
// runs when it's false
}
The condition goes in brackets. In C, a condition is just a number: 0 means false, anything else means true. Comparisons like age >= 18 produce 1 (true) or 0 (false).
int age = 20;
if (age >= 18) {
printf("You can vote\n");
} else {
printf("Not yet\n");
}
The else part is optional — leave it out when there's nothing to do on the false side.
Try it
Change temperature and run it again — try 30, then 31.
#include <stdio.h>
int main(void) {
int temperature = 34;
if (temperature > 30) {
printf("It's hot. Drink water.\n");
} else {
printf("Nice weather.\n");
}
printf("Done.\n");
return 0;
}output
It's hot. Drink water.
Done.Run and edit it in the app.
Done. prints either way — it's outside both blocks.
Reading input and deciding
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
if (n % 2 == 0) {
printf("%d is even\n", n);
} else {
printf("%d is odd\n", n);
}
return 0;
}input
7output
7 is oddRun and edit it in the app.
Watch it
Think of it like
A fork in a road with a sign: "If it's raining, take the covered path; otherwise take the park." You only walk one of the two paths.
🕷️ Spidey-sense: My spidey-sense is basically one big
if. If danger, dodge. Else, keep eating my sandwich.
Common mistake
A semicolon right after the condition:
if (age >= 18); // ✗ this ; is an empty statement — the if ends here
{
printf("Vote!\n"); // so this block ALWAYS runs
}
The compiler accepts it, which makes it hard to spot. No ; after if (...).
Key terms
- Condition — An expression that's true (non-zero) or false (zero).
- Block — Code grouped in
{ }. - Branch — One of the paths an
if/elsecan take.
Check yourself
When does the else block run?
In C, which value counts as false?
What's wrong with if (x > 5); { … } ?