In this tutorial we will learn writing java program to find the smallest number among the three given numbers. This program will be very simple. Here we are just comparing the numbers using if else statements. And after comparing we will just print the smallest number.
How program will behave?
Our program will take 3 numbers as an input. Now using if else statements we will compare the numbers. Logic of comparison will be like a<=b && a<=c. Here a is smaller because it is smaller than b and c both. For the input 3, 4 and 5, output will be 3.
Java Program to Calculate Smallest Among Three
import java.util.*;
public class Main {
public static void main(String[] args) {
int a, b, c;
Scanner sc = new Scanner(System.in);
System.out.println("Please give the first number");
a= sc.nextInt();
System.out.println("Please give the second number");
b= sc.nextInt();
System.out.println("Please give the third number");
c= sc.nextInt();
if(a<=b && a<=c)
System.out.println("a is smallest");
if(b<=a && b<=c)
System.out.println("b is smallest");
if(c<=a && c<=b)
System.out.println("c is smallest");
}
}
Output
Please give the first number
67
Please give the second number
34
Please give the third number
22
c is smallest
Explanation
The user inputs the integers 6, 2, 7. For these inputs, our program is comparing all three integer inputs with each other to find which one is the smallest. Let’s have a look at the conditions of conditional statements in this
output: 6<=2 and 6<=9, returns ‘False’, 2<=6 and 2<=9, returns ‘True’ , 9<=6 and 9<2, returns ‘False’
So the output is ‘b’ because b value 2 is smallest.