Here we are explaining how to write a java program to find out the largest of three numbers using the ternary operator. We have to accept three numbers from the user into the variable a,b,c. Then by using the ternary operator we will find out the largest of a,b,c.
The conditional operator is also known as the ternary operator. The ternary operator has mainly three operands. The ternary operator can be written as,
Variable x=(Condition)?if the condition is true x has this value: if the condition is false x has this value;
Example: variable t = a > b ? a:b;
Here if a > b then t becomes a.Else t becomes b.
First we have to declare the class Smallest .Declare the integer variables a,b,c,l,t.Read three numbers from the user into the variable a,b,c.Then by using the ternary operator check a > b,if true then t =a,otherwise t=b.Then using another ternary operator check c > t ,if true then l = c otherwise l = t.Then display l.
STEP 1: Declare the class Largest with a public modifier.
STEP 2: Open the main() to start the program, Java program execution starts with the main()
STEP 3: Declare the integer variables a,b,c,l,t as integer.
STEP 4: Read the first number into the variable a.
STEP 5: Read the second number into the variable b.
STEP 6: Read the third number into the variable c.
STEP 7: By using ternary operator check a > b,if true then set t = a.Else t = b.
STEP 8: By using another ternary operator check c > t,if true then set l = c, Else l = t.
STEP 9: Display the largest number as l.
import java.util.Scanner;
public class Largest
{
public static void main(String[] args)
{
int a,b,c,l,t;
Scanner sc = new Scanner(System.in);
System.out.println("Enter The First Number:");
a = sc.nextInt();
System.out.println("Enter The Second Number:");
b = sc.nextInt();
System.out.println("Enter The Third Number:");
c = sc.nextInt();
sc.close();
t = a > b ? a:b;
l = c > t ? c:t;
System.out.println("The Largest Number is:"+l);
}
}
Enter The First Number:100 Enter The Second Number:12 Enter The Third Number:600 The Largest Number is:600