In this tutorial we will find the smallest of three numbers . We can find min of 3 numbers in java using different methods . Let’s discuss these method steps by steps.
Example 1 – Find Smallest of Three Numbers using If-Else
In this example we will see how to find the minimum value in java using if-else . First we write algorithm to find smallest of 3 numbers .
Algorithm to Find Smallest of 3 Numbers Using if-else :
- Take input from user for three numbers and store in variables a, b, c.
- Now check if variable a is less than b.
- If above condition is true,then go to step 4, else go to step 6.
- Now check if a is less than c.
- If above condition is true, then a is the smallest, else c is the smallest. Go to step 8.
- Now check if b is less than c.
- If above condition is true,then b is the smallest, else c is the smallest.
- Print value of smallest variable .
Now we will implement above algorithm and write a java program to find smallest of three numbers.
import java.util.Scanner;
public class MinimumOfThreeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number : ");
int a = scanner.nextInt();
System.out.println("Enter second number : ");
int b = scanner.nextInt();
System.out.println("Enter third number : ");
int c = scanner.nextInt();
int min;
// find the min using if else
if (a < b) {
if (a < c) {
min = a;
} else {
min = c;
}
} else {
if (b < c) {
min = b;
} else {
min = c;
}
}
//print minimum number
System.out.println(min + " is the smallest.");
//close scanner
scanner.close();
}
}
Output:
Enter first number :
10
Enter second number :
20
Enter third number :
30
10 is the smallest.
Example 2– Smallest of Three numbers using Ternary Operator in Java
Now , In this example we will compare 3 numbers in java ternary operator . This is one line code to find the minimum value of three numbers in java. Let’s java program to find the smallest of three numbers using ternary operator. In this program we have used ternary operator .
import java.util.Scanner;
public class MinimumOfThreeNumbers2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number : ");
int a = scanner.nextInt();
System.out.println("Enter second number : ");
int b = scanner.nextInt();
System.out.println("Enter third number : ");
int c = scanner.nextInt();
//find the smallest using nested ternary operator
int largest = (a < b) ? (a < c ? a : c) : (b < c ? b : c);
//print smallest number
System.out.println(largest + " is the smallest.");
//close scanner
scanner.close();
}
}
Output:
Enter first number :
20
Enter second number :
10
Enter third number :
70
10 is the smallest.
In this tutorial we have learned algorithm to find smallest of 3 numbers and java program to find the smallest of three numbers . You can see more java program for practice .