C If...Else
The if statement lets a program execute code only when a condition is true. You can extend it with else if to check further conditions, and else to provide a default action.
Conditions are placed inside parentheses after if, and the code to run is placed inside curly braces.
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}Basic if / else
An if statement runs a block only if its condition is true. Adding an else block provides an alternative action when the condition is false.
Chaining with else if
else if lets you test multiple conditions in sequence; the first one that's true runs, and the rest are skipped.
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18) {
printf("Adult\n");
} else {
printf("Minor\n");
}
return 0;
}AdultSince age is 20, the condition is true, so 'Adult' is printed.
#include <stdio.h>
int main() {
int score = 75;
if (score >= 90) {
printf("A\n");
} else if (score >= 70) {
printf("B\n");
} else {
printf("C\n");
}
return 0;
}BThe first true condition (score >= 70) determines which branch runs.
Key points
- if runs code only when its condition is true.
- else if chains additional conditions.
- else provides a default when no condition is true.
- Conditions must be enclosed in parentheses.
