Here we are explaining how to write a java program to find out the smallest 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 smallest 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 v=(Condition)? value1: value2; if the condition is true v have the value1 and if the condition is false v have value2.
Example: 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,s_val,tmp.Read three numbers from the user into the variable a,b,c.Then by using the ternary operator check a < b,if true then tmp =a,otherwise tmp=b.Then using another ternary operator check c < tmp ,if true then s_val = c otherwise s_val = tmp.Then display s_val.
STEP 1: Declare the class Smallest 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,s_val,tmp 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 tmp = a,else tmp=b.
STEP 8: By using another ternary operator check c < tmp,if true then set s_val=c,else s_val= tmp.
STEP 9: Display the smallest number as s_val.
import java.util.Scanner;
public class Smallest
{
public static void main(String[] args)
{
int a,b,c,s_val,tmp;
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();
tmp = a < b ? a:b;
s_val = c < tmp ? c:tmp;
System.out.println("The Smallest Number is:"+s_val);
}
}
Enter The First Number:10 Enter The Second Number:2 Enter The Third Number:99 The Smallest Number is:2