C if-else Statement
In this page:
What is if-else?
if-else covers exactly two possible outcomes for a condition: the if block runs when the condition is true, and the else block runs instead whenever it's false, so exactly one of the two paths always executes.
Example: What is if-else?
#include <stdio.h>
int main() {
int age = 15;
if (age >= 18) {
printf("Adult");
} else {
printf("Minor");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Pass or Fail Check
Comparing a score against a passing threshold with if-else -- if (score >= 50) ... else ... -- cleanly separates the pass and fail outcomes into two distinct, mutually exclusive code paths.
Example: Pass or Fail Check
#include <stdio.h>
int main() {
int score = 40;
if (score >= 50) {
printf("Pass");
} else {
printf("Fail");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Even or Odd Divider
Testing n % 2 == 0 inside an if-else lets a single conditional handle both the even and odd cases in one block, rather than needing two separate if statements to cover both outcomes.
Example: Even or Odd Divider
#include <stdio.h>
int main() {
int n = 7;
if (n % 2 == 0) {
printf("Even");
} else {
printf("Odd");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Voting Eligibility
if-else is a natural fit for eligibility checks, such as verifying if (age >= 18) ... else ... to separate users who qualify for something from those who don't, in a single readable comparison.
Example: Voting Eligibility
#include <stdio.h>
int main() {
int age = 16;
if (age >= 18) {
printf("Can vote");
} else {
printf("Cannot vote");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested if-else
Nesting an if-else inside either branch of an outer if-else lets you handle sub-decisions -- for example, once you know a number is positive, a nested if-else can further classify it as even or odd.
Example: Nested if-else
#include <stdio.h>
int main() {
int n = 8;
if (n > 0) {
if (n % 2 == 0) {
printf("Positive even");
} else {
printf("Positive odd");
}
} else {
printf("Not positive");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: