If else in C: solved exercises with nested conditions

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:

  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.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#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

1
2
3
4
-8 is negative
Score 76 => Good
Year 2024 leap: yes
Access (17, permission=1): allowed

Common mistakes

  • 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.

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.

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.