C++ else if statment

To show a multi-way decision based on several conditions, we use the else if statement.

Syntax :
 if(condition_2)
 {
    block 1 statement;
 }
 else if (condition_2)
 {
    block 2 statement;
 }
 else if(condition_n)
 {
    block n statement;
 }
 else
 {
    block x statement;
 }

here, the conditions are evaluated in order from top to bottom. As soon as any condition evaluates to true, then statement associated with the given condition is executed and if all condition are false, then control is transferred to statement_x skipping the rest of the condition.
Example :

#include <iostream>
using namespace std;
int main ()
{
    int mark;

    cout<<"Enter total marks of student : ";
    cin>>mark;

    if(mark <= 50)
    {
        cout<<"\nGrade D";
    }
    else if (mark <= 60)
    {
        cout<<"\nGrade C";
    }
    else if (mark <= 70)
    {
        cout<<"\nGrade B";
    }
    else
    {
        cout<<"\nGrade A";
    }

    return 0;
}
Output :
 Enter total marks of student : 80
 Grade A

0 Comments