Ladder if-else statement

The ladder if-else statement is used to check the set of conditions in sequence. The ladder if-else statement is similar to if-else, but here we can check multiple conditions one after one until a condition is evaluated as true.

Syntax

if (<condition 1>) {

    // Code to be executed if condition 1 is true

} else if (<condition 2>) {

    // Code to be executed if condition 2 is true

} else if (<condition 3>) {

    // Code to be executed if condition 3 is true

}

// N number of else if...

else {

    // Code to be executed if all the conditions are false

}

Example

In this program, we are going to find a grade for a student from the given percentage of all marks.

import java.util.Scanner;

public class LadderIfElseExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter percentage : ");
        int percentage = scanner.nextInt();

        // ladder if else statement
        if (percentage >= 90) {

            System.out.println("A+ Grade");

        } else if (percentage >= 80) {

            System.out.println("A Grade");

        } else if (percentage >= 70) {

            System.out.println("B Grade");

        } else if (percentage >= 60) {

            System.out.println("C Grade");

        } else if (percentage >= 50) {

            System.out.println("D Grade");

        } else {

            System.out.println("Fail!");

        }
        
    }
}

Flow diagram

Flow-diagram of the above example program –