if
if runs a block of code only when its condition is true:
#include <stdio.h>
int main() {
int temperature = 32;
if (temperature > 30) {
printf("It's hot today!\n");
}
printf("Have a nice day.\n");
return 0;
}Output
It's hot today! Have a nice day.
The condition goes in round brackets ( ). The code to run goes in curly braces { }. The last line runs every time, because it is outside the braces.
else
else gives the other path: what to do when the condition is false.
#include <stdio.h>
int main() {
int age;
scanf("%d", &age);
if (age >= 18) {
printf("You can vote.\n");
} else {
printf("You can vote in %d years.\n", 18 - age);
}
return 0;
}Input (what the user types)
15
Output
You can vote in 3 years.
else if: more than two choices
Chain several conditions with else if. C checks them from top to bottom and runs only the first one that is true:
#include <stdio.h>
int main() {
int marks;
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("Try again\n");
}
return 0;
}Input (what the user types)
82
Output
Grade B
82 is not ≥ 90, but it is ≥ 75, so C prints Grade B and skips the rest.
Think of it like this: An
if/else ifchain is like a sorting machine for letters: each letter falls into the first slot it fits, and never into two.
Even or odd?
A classic example using %:
#include <stdio.h>
int main() {
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 (what the user types)
7
Output
7 is odd
Common mistake: Putting a semicolon after the condition:
if (x > 5);. The;ends theifright there, so the block after it always runs.
Tip: Always use curly braces, even for one line. It keeps your code clear and safe when you add more lines later.