Java Program - Smallest of Three NumbersΒΆ
Prerequisites: If-Else-If Ladder, Logical Operators (&&)
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