Menu
Topics Index
...
`


Control Statements > Selection Statements >
Siva Nookala - 22 Feb 2019
It is very common in programming to have more than two ways (or branches). e.g., printing the grade of a student like "Distinction", "First Class", "Second Class" and "Fail" instead of simply "Pass" or "Fail". In this case if-else-if ladder will be very useful.


    if( condition1 )
    {
        statement1; // BLOCK 1
    }
    else if( condition2 )
    {
        statement2; // BLOCK 2
    }
    else if( condition3 )
    {
        statement3; // BLOCK 3
    }
    else
    {
        statement4; // BLOCK 4
    }

The above if conditions are executed top down. If the condition1 is true, only statement1 is executed, the other statements - statement2 and statement3 will not be executed.
If the condition1 is false and condition2 is true, then only statement2 is executed. If condition1, condition2 are false but condition3 is true, then only statement3 is executed. If all the conditions - condition1, condition2 and condition3 are false, then statement4 is executed.
Also note that when condition1 is true, irrespective of whether other conditions are true or false, only statement1 will be executed. statement2 and statement3 will not be executed.
Print Student Grade
class PrintStudentGrade
{
    public static void main(String arg[])
    {
        int marks = 65;
        
        if( marks > 75 )      // CONDITION A
        {
            System.out.println("Distinction"); // LINE A
        }
        else if( marks > 60 ) // CONDITION B
        {
            System.out.println("First Class"); // LINE B
        }
        else if( marks > 50 ) // CONDITION C
        {
            System.out.println("Second Class"); // LINE C
        }
        else
        {
            System.out.println("Fail");  // LINE D
        }
    
    }
}
OUTPUT

First Class

DESCRIPTION

Since the marks are 65, the CONDITION A will be false, so the CONDITION B in the else is executed. Since CONDITION B is true, LINE B is executed printing First Class.

THINGS TO TRY
  • Change the marks to 75, 53 and 32 and see the output in each case.
  • Try removing the else conditions and see the result with various values.
  • Change the program to achieve the same functionality with out using the else block.

2-min video about if-else-if ladder

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App