Problem Solving using C Language

0 of 77 lessons complete (0%)

Conditional Statement

else-if Statement

An else if statement in programming is a conditional statement used to check multiple conditions one after another. It allows the program to evaluate a series of conditions in a sequence. If the first condition (if) is false, it moves to the else if statement to check another condition. This process continues until it finds a condition that is true or reaches the else block (if provided).

Structure of if-else if statement:

if (condition1) {
    // Code block executed if condition1 is true
}
else if (condition2) {
    // Code block executed if condition1 is false and condition2 is true
}
else if (condition3) {
    // Code block executed if both condition1 and condition2 are false, but condition3 is true
}
else {
    // Code block executed if all previous conditions are false
}

Example:

Imagine a grading system where we assign grades based on marks:

#include <stdio.h>

int main() {
    int marks;

    // Ask the user to enter their marks
    printf("Enter your marks (0-100): ");
    scanf("%d", &marks);

    // Check for valid input
    if (marks < 0 || marks > 100) {
        printf("Invalid marks! Please enter a value between 0 and 100.\n");
    }
    // Determine the grade based on the marks
    else if (marks >= 90) {
        printf("Grade: A\n");
    }
    else if (marks >= 80) {
        printf("Grade: B\n");
    }
    else if (marks >= 70) {
        printf("Grade: C\n");
    }
    else if (marks >= 60) {
        printf("Grade: D\n");
    }
    else if (marks >= 50) {
        printf("Grade: E\n");
    }
    else {
        printf("Grade: F (Fail)\n");
    }

    return 0;
}

Explanation:

  1. The program prompts the user to input their marks between 0 and 100.
  2. The if condition first checks if the input marks are valid (i.e., between 0 and 100).
  3. Then, based on the value of marks, the program assigns a grade using a series of else if statements:
    • A for marks 90 or above
    • B for marks between 80 and 89
    • C for marks between 70 and 79
    • D for marks between 60 and 69
    • E for marks between 50 and 59
    • F (Fail) for marks below 50
  4. If the user enters marks outside the valid range, an error message is printed.