In this program, we are going to find the largest number among three numbers, similar to the previous one, but it is nested if-else version.
Logic
Let three variables be: A = 400, B = 200 and C = 300
The logic goes like this:
- if A >= B then check for if A >= C, then print A else print C.
- else part: if B >= C then print B else print C.
See the below-shown flow diagram to better understand.
Program
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter 1st number : "); int num1 = scanner.nextInt(); System.out.println("Enter 2nd number : "); int num2 = scanner.nextInt(); System.out.println("Enter 3rd number : "); int num3 = scanner.nextInt(); if(num1 >= num2) { if(num1 >= num3) { System.out.println(num1 + " is largest number"); } else { System.out.println(num3 + " is largest number"); } } else { if(num2 >= num3) { System.out.println(num2 + " is largest number"); } else { System.out.println(num3 + " is largest number"); } } } }
Output
Enter 1st number : 100
Enter 2nd number : 10
Enter 3rd number : 99
100 is largest number