. Write
a
program to find greatest number
three numbers.
among
110
Answers
Answer:
variable_name = (expression) ? value if true:value if false
import java.util.Scanner;
public class LargestNumberExample1
{
public static void main(String[] args)
{
int a, b, c, largest, temp;
//object of the Scanner class
Scanner sc = new Scanner(System.in);
//reading input from the user
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();
//comparing a and b and storing the largest number in a temp variable
temp=a>b?a:b;
//comparing the temp variable with c and storing the result in the variable
largest=c>temp?c:temp;
//prints the largest number
System.out.println("The largest number is: "+largest);
}
}
Output:
Enter the first number:
23
Enter the second number:
11
Enter the third number:
67
Largest Number is: 67
We can also compare all the three numbers by using the ternary operator in a single statement. If we want to compare three numbers in a single statement, we must use the following statement.
d = c > (a>b ? a:b) ? c:((a>b) ? a:b);
In the following program, we have used a single statement to find the largest of three numbers.
LargestNumberExample2.java
import java.util.Scanner;
public class LargestNumberExample2
{
public static void main(String[] args)
{
int a, b, c, largest;
//object of the Scanner class
Scanner sc = new Scanner(System.in);
//reading input from the user
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();
largest = c > (a > b ? a : b) ? c : ((a > b) ? a : b);
System.out.println("The largest number is: "+largest);
}
}
mark me as brainliest
mark me as brainliest
mark me as brainliest
mark me as brainliest