else if statement in C

In this program we’ll show you the usage of else-if clause in C programming language. Here we are illustrating the concept by taking score/marks of 5 subject from the user. Then we calculate the percentage of it and display grade to the user.

Related Read:
Nested if else Statement In C

Simple Logic: Student Grade

First in if‘s condition we check if the user entered percentage is above 100%. If true – in that case we let the user know that he entered wrong marks and he / she needs to re-enter the marks. Next in first else if we check if the percentage is greater than or equal to 60. Here we need not check if the percentage is less than 100, because in if clause itself we’ve checked if percentage is greater than 100, and we are checking the else if condition only because the condition in if is false. So percentage will be less than 100. Same logic goes to consecutive Grades.

Student Grade Calculation using else if clause: C Program



YouTube Link: https://www.youtube.com/watch?v=WmJEbiKX4BA [Watch the Video In Full Screen.]


Note: When the condition is true, it executes its corresponding block of code and then skips checking remaining else if or else conditions.

Note: Its optional to have else in if or else if clause.

Note: We can have any number of else if statements after if.

Student Grade Calculation using else-if clause

 
#include < stdio.h >

int main()
{
    int s1, s2, s3, s4, s5, per;

    printf("Enter marks of 5 subjects\n");
    scanf("%d %d %d %d %d", &s1, &s2, &s3, &s4, &s5);

    per = (s1 + s2 + s3 + s4 + s5) / 5.0;

    if(per > 100)
        printf("You've entered wrong marks, kindly re-enter\n");
    else if(per >= 60)
        printf("Grade A\n");
    else if(per >= 50)
        printf("Grade B\n");
    else if(per >= 40)
        printf("Grade C\n");
    else
        printf("Failed!\n");

    return 0;
}

Output 1:
Enter marks of 5 subject
59
60
62
61
63
Grade A

Output 2:
Enter marks of 5 subject
59
55
56
53
58
Grade B

Output 3:
Enter marks of 5 subject
49
45
46
49
48
Grade C

Output 4:
Enter marks of 5 subject
39
45
25
36
35
Failed!

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert