If else in C: solved exercises with nested conditions

  2 minutes

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.

Solve these 4 mini exercises:

  1. classify a number as positive, negative, or zero,
  2. map a numeric score to a grade range,
  3. determine whether a year is leap year,
  4. validate access using two logical conditions.
#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;
}
-8 is negative
Score 76 => Good
Year 2024 leap: yes
Access (17, permission=1): allowed
  • Using separate if blocks when you need else if.
  • Writing long logical conditions without parentheses.
  • Missing edge cases (for example exact boundaries like 50 or 70).
  • Over-nesting instead of simplifying conditions.

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.

If you want a complete path with progressive difficulty:

Use if else if when conditions are mutually exclusive. Use separate if blocks when multiple conditions can be true at the same time.

Split it into well-named intermediate boolean variables. This improves readability and lowers bug risk.

Not by default, but deep nesting usually signals that you should simplify rules or extract helper functions.