Largest among three numbers in java
How to find the largest among three numbers using Java programming language.
Approach :- 1 "Largest among three numbers in java using if-else statement"
package asicQuestion;
import java.util.Scanner;
public class largerNO {
public static void main(String[] args) {
int num1, num2, num3;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: ");
num1 = sc.nextInt();
System.out.println("Enter the second number: ");
num2 = sc.nextInt();
System.out.println("Enter the third number: ");
num3 = sc.nextInt();
if (num1 > num2 && num1 > num3) {
System.out.println(num1 +" is greater than "+num2+" and "+num3);
} else if (num2 > num1 && num2 > num3) {
System.out.println(num2 +" is greater than "+num1+" and "+num3);
} else {
System.out.println(num3 +" is greater than "+num1+" and "+num2);
}
}
}
Output :-
Approach :- 2 "Find largest number using nested if-else"
package asicQuestion;
import java.util.Scanner;
public class largestNo {
public static void main(String[] args){
int num1 = 4, num2 = 7, num3 = 13;
if(num1 > num2){
if(num1 > num3){
System.out.println(num1 +" is greater than "+num2+" and "+num3);
}
else{
System.out.println(num3 +" is greater than "+num1+" and "+num2);
}
}
else{
if(num2 > num3){
System.out.println(num2 +" is greater than "+num1+" and "+num3);
}
else{
System.out.println(num3 +" is greater than "+num1+" and "+num2);
}
}
}
}
Approach:- 3 " using ternary operator"
package asicQuestion;
public class largeNumUsingTernary {
public static void main(String[] args){
int num1 = 24, num2 = 14, num3 = 8;
int result = num1 > (num2 > num3 ? num2 : num3) ? num1 : ((num2 > num3)?num2:num3);
System.out.println("The largest number is: "+result);
}
}
Logic explanation
- How to determine the largest among three numbers, first we have to take three integer numbers. Let's it be num1, num2, num3.
- See if num1 is greater than num2 as well as num3, then num1 will be the greatest number among num2 and num3.
- Ex:- (num1 > num2) && (num1 > num3)
- Like this if num2 is greater than num1 and num 3, then num2 will be the greatest number.
- Ex:- (num2 > num1) && (num2 > num3)
- If the above two conditions are not satisfied, then num3 will automatically be greatest number.
Logic for largest number using ternary operator
int result = num3 > (num1 > num2 ? num1 : num2) ? num3 : ((num1 > num2) ? num1 : num2);
Ex:- num1 = 4, num2 = 6, num3 = 5
- result = 5 > ( 4 > 6 ? num1 : num2 ) ? num3 : (( 4 > 6 ) ? num1 : num2);
- => result = 5 > 6 ? num3 : 6
- => result = 6
Also read :-
- Even Odd in java :- click here
- Array input in java :- click here