Home » Blog » Find Maximum From Three Number By Using Ternary Operator

# Find Maximum From Three Number By Using Ternary Operator

The Ternary Operator is an operator that takes three arguments. The first argument is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison. If it helps you can think of the operator as shortened way of writing an if-else statement.

Let’s take three numbers from user. If the numbers are two then find maximum from that numbers are much easier by using Ternary Operator as formula int max = num1 > num2 ? num1 : num2;

But we have three numbers, so that it is a little complex as compare to case that have two numbers. We can use formula as below.

int max = num3 > (num1 > num2 ? num1 : num2) ? num3 : ((num1 > num2) ? num1 : num2);

First we know that if number 3 is greater then number1 and number 2 for that we use Ternary Operaor inside Ternary Operator. By using this we find maximum number from number 1 and number 2 (num1 > num2 ? num1 : num2); and then compare it with number 3. If number 3 is maximum then it will directly assign to variable but if not then it will again check that the number 1 is grater or number 2 is greater by using num1 > num2 ? num1 : num2; this. And Finally we get maximum number from given three numbers.

```import java.util.*;
public class maxofthree
{

public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a,b,c,large;

System.out.println("***Maximum Out of three***");
System.out.println("Enter first value =");
a=sc.nextInt();
System.out.println("Enter second value =");
b=sc.nextInt();
System.out.println("Enter third value =");
c=sc.nextInt();

large=c>(a>b?a:b)?c:((a>b)?a:b);

System.out.println("Maximum Number is = "+large);
}

}```

Here is the OutPut

```***Maximum Out of three***
Enter first value =
23
Enter second value =
41
Enter third value =
51
Maximum Number is = 51```