In this program, we are going to see how to find the largest number among three numbers using if statement.
Logic
Here we have to compare each number with another two numbers, if it is greater than the both then simply print it.
Let’s say A = 11, B = 22 and C = 15
Then steps would be
- if A > B and A > C that means A is the largest number.
- if B > A and B > C that means B is the largest number.
- Similarly if C > A and C > B that means C is the largest number.
Program
import java.util.Scanner; public class IfStatement { 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 && num1 >= num3) { System.out.println(num1 + " is largest number"); } if(num2 >= num1 && num2 >= num3) { System.out.println(num2 + " is largest number"); } if(num3 >= num1 && num3 >= num2) { System.out.println(num3 + " is largest number"); } } }
Output
Enter 1st number : 10
Enter 2nd number : 5
Enter 3rd number : 11
11 is largest number