If else in C: solved exercises
If you are searching for conditional exercises in C, this guide covers practical cases with if, if else, if else if, and nested conditions.
The goal is to write clear decisions and avoid unnecessary branches.
Problem statement
Solve these 4 mini exercises:
- classify a number as positive, negative, or zero,
- map a numeric score to a grade range,
- determine whether a year is leap year,
- validate access using two logical conditions.
C solution
#include <stdio.h>
void classify_number(int n) {
if (n > 0) {
printf("%d is positive\n", n);
} else if (n < 0) {
printf("%d is negative\n", n);
} else {
printf("%d is zero\n", n);
}
}
const char *grade_label(int score) {
if (score >= 90) return "Excellent";
else if (score >= 70) return "Good";
else if (score >= 50) return "Pass";
else return "Fail";
}
int is_leap_year(int year) {
if (year % 400 == 0) return 1;
if (year % 100 == 0) return 0;
if (year % 4 == 0) return 1;
return 0;
}
int access_allowed(int age, int has_permission) {
if (age >= 18 || (age >= 16 && has_permission)) {
return 1;
}
return 0;
}
int main(void) {
classify_number(-8);
printf("Score 76 => %s\n", grade_label(76));
printf("Year 2024 leap: %s\n", is_leap_year(2024) ? "yes" : "no");
printf("Access (17, permission=1): %s\n",
access_allowed(17, 1) ? "allowed" : "denied");
return 0;
}Expected output
-8 is negative
Score 76 => Good
Year 2024 leap: yes
Access (17, permission=1): allowedCommon mistakes
- Using separate
ifblocks when you needelse if. - Writing long logical conditions without parentheses.
- Missing edge cases (for example exact boundaries like 50 or 70).
- Over-nesting instead of simplifying conditions.
Practical use
Conditionals are core in:
- input validation,
- business rules,
- access control,
- result classification by ranges.
Strong if else fundamentals improve all control-flow problem solving in C.
Recommended next exercise
- While and do while in C: solved exercises
- For loop in C: solved exercises with accumulators and counters
- Sequential programming in C: solved exercises from scratch
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
When should I use if else if instead of multiple if blocks?
Use if else if when conditions are mutually exclusive. Use separate if blocks when multiple conditions can be true at the same time.
What if the condition becomes too long?
Split it into well-named intermediate boolean variables. This improves readability and lowers bug risk.
Are nested conditionals bad in C?
Not by default, but deep nesting usually signals that you should simplify rules or extract helper functions.