C - nested if-else

In C, if statement within another if statement is called nested if statement. Similarly you can use nested if-else statements to create complex decision-making structures where you have multiple conditions to evaluate. Nesting means placing one if-else statement inside another, forming a hierarchy of conditions and code blocks. Each nested if-else statement can have its own set of conditions and actions.

For example, imagine you want to decide what to wear based on the weather. You could say:

"If it's sunny, wear shorts. But if it's not sunny, then check if it's raining. If it's raining, wear a raincoat. If it's not raining, wear jeans."

Here, you have a main decision about sunny or not sunny weather, and inside that decision, there are more decisions about rain and clothing choices. This is similar to how nested if-else statements work in programming, where you have one if-else statement inside another to handle different conditions and actions.

Here's the general syntax of a nested if-else statement:


if (condition1) {
    // Code to execute if condition1 is true
    if (condition2) {
        // Code to execute if both condition1 and condition2 are true
    } else {
        // Code to execute if condition1 is true but condition2 is false
    }
} else {
    // Code to execute if condition1 is false
}

Here's an example that uses nested if-else statements to determine the grade of a student based on multiple criteria, including attendance and exam score:


#include <stdio.h>

int main() {
    int attendance, score;

    printf("Enter attendance percentage: ");
    scanf("%d", &attendance);

    printf("Enter exam score: ");
    scanf("%d", &score);

    if (attendance >= 75) {
        if (score >= 90) {
            printf("Grade: A\n");
        } else {
            printf("Grade: B\n");
        }
    } else {
        printf("Grade: F (Fail)\n");
    }

    return 0;
}

In this example:

  1. The program asks the user to input attendance percentage and exam score.
  2. It uses a nested if-else structure. First, it checks if the attendance is greater than or equal to 75%. If attendance is sufficient, it further evaluates the exam score to determine the grade ('A' or 'B').
  3. If attendance is below 75%, the program assigns a grade of "F" (Fail).

Nested if-else statements allow you to handle more complex decision scenarios by breaking them down into multiple levels of conditions and actions. Each level of nesting introduces additional criteria for decision-making.