C If Else
Programs become useful when they can make choices. The if statement lets your code run some instructions only when a condition is true, and the else part lets it run something different when the condition is false. This is how a program reacts to different situations.
The if statement
An if statement checks a condition inside parentheses. If that condition is true (any non-zero value), the block of code in the curly braces runs. If it is false, the block is skipped entirely.
A simple if
#include <stdio.h>
int main() {
int temperature = 30;
if (temperature > 25) {
printf("It is a hot day.\n");
}
return 0;
}Adding else
The else keyword gives your program a fallback. When the if condition is false, the else block runs instead. Exactly one of the two blocks will always run.
if with else
#include <stdio.h>
int main() {
int hour = 20;
if (hour < 18) {
printf("Good day.\n");
} else {
printf("Good evening.\n");
}
return 0;
}The else if ladder
Sometimes you have more than two possibilities. You can chain conditions with else if. C checks each condition from top to bottom and runs the first block whose condition is true; the rest are skipped.
Grading with else if
#include <stdio.h>
int main() {
int score = 82;
if (score >= 90) {
printf("Grade A\n");
} else if (score >= 75) {
printf("Grade B\n");
} else {
printf("Grade C\n");
}
return 0;
}- if runs its block only when the condition is true.
- else if lets you test another condition when earlier ones failed.
- else is the catch-all that runs when nothing above matched.
Exercise: C If...Else
In `if (a > b) x = 1; y = 2;`, when does the line y = 2 execute?