Java Program - Smallest of Three Numbers¶
Concept Explanation¶
What is it?¶
This program compares three numerical values provided by the user and determines which one is the lowest.
Real-world example¶
Imagine you have three prices for the same product from different stores. This program helps you find the cheapest option.
Algorithm¶
- Start
- Input three numbers:
a,b, andc. - Check if
ais smaller than bothbandc. - Check if
bis smaller than bothaandc. - Otherwise,
cis the smallest. - Display the smallest number.
- End
Implementations¶
import java.util.Scanner;
public class SmallestNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter three numbers:");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int smallest;
if (a <= b && a <= c) {
smallest = a;
} else if (b <= a && b <= c) {
smallest = b;
} else {
smallest = c;
}
System.out.println("The smallest number is: " + smallest);
sc.close();
}
}
Explanation¶
- Java
- Logical AND (&&): Used to combine two conditions. Both must be true for the whole expression to be true.
- Comparison Operators (<=): Handles cases where numbers might be equal.
Complexity Analysis¶
- Time Complexity: O(1)
- Space Complexity: O(1)
Related Concepts¶
"Logic will get you from A to B. Imagination will take you everywhere." - Albert Einstein