Greater of Two Numbers¶
Concept Explanation¶
What is it?¶
This program takes two numerical inputs and determines which of them is larger. It's a fundamental comparison operation used in almost all programming contexts to control program flow based on data relationships.
Why is it important?¶
Comparing values is a cornerstone of decision-making in programming. Whether it's sorting data,
validating input, or controlling game logic, the ability to determine which value is greater (or
smaller, or equal) is essential. This simple exercise introduces the core if-else construct.
Where is it used?¶
- Sorting Algorithms: Used repeatedly to order elements in lists or arrays.
- Input Validation: Ensuring a minimum or maximum threshold for user-entered data.
- Game Logic: Deciding which player has a higher score, or if a character's health is below a certain point.
- Financial Calculations: Comparing prices, balances, or transaction amounts.
Real-world example¶
Imagine you're buying groceries and comparing the prices of two different brands of milk. You want to buy the cheaper one. This is a real-world comparison that directly maps to finding the "lesser" of two numbers, which is the inverse of finding the "greater."
Algorithm¶
- Start.
- Get two numbers (
num1,num2) from the user. - If
num1is greater thannum2: a. Displaynum1as greater. - Else if
num2is greater thannum1: a. Displaynum2as greater. - Else (if
num1is equal tonum2): a. Display that both numbers are equal. - End.
Edge Cases:
- Non-numeric input (handled by language-specific error mechanisms or explicit validation).
- Floating-point comparisons: Direct equality (==) checks with floats can be problematic due to precision issues; using a small epsilon value for "near equality" is often preferred for more robust comparisons. This example uses direct comparison for simplicity.
Implementations¶
import java.util.Scanner;
public class GreaterOfTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.println("Numbers entered: " + num1 + ", " + num2);
if (num1 > num2) {
System.out.println(num1 + " is greater than " + num2);
} else if (num2 > num1) {
System.out.println(num2 + " is greater than " + num1);
} else {
System.out.println("Both numbers are equal: " + num1);
}
scanner.close();
}
}
# Get two numbers from the user
num1_str = input("Enter the first number: ")
num1 = float(num1_str)
num2_str = input("Enter the second number: ")
num2 = float(num2_str)
print(f"Numbers entered: {num1}, {num2}")
if num1 > num2:
print(f"{num1} is greater than {num2}")
elif num2 > num1:
print(f"{num2} is greater than {num1}")
else:
print(f"Both numbers are equal: {num1}")
#include <stdio.h>
int main() {
double num1, num2;
printf("Enter the first number: ");
scanf("%lf", &num1);
printf("Enter the second number: ");
scanf("%lf", &num2);
printf("Numbers entered: %.2lf, %.2lf\n", num1, num2);
if (num1 > num2) {
printf("%.2lf is greater than %.2lf\n", num1, num2);
} else if (num2 > num1) {
printf("%.2lf is greater than %.2lf\n", num2, num1);
} else {
printf("Both numbers are equal: %.2lf\n", num1);
}
return 0;
}
SET SERVEROUTPUT ON;
DECLARE
num1 NUMBER := &Enter_First_Number;
num2 NUMBER := &Enter_Second_Number;
BEGIN
DBMS_OUTPUT.PUT_LINE('First Number: ' || num1);
DBMS_OUTPUT.PUT_LINE('Second Number: ' || num2);
IF num1 > num2 THEN
DBMS_OUTPUT.PUT_LINE(num1 || ' is greater than ' || num2);
ELSIF num2 > num1 THEN
DBMS_OUTPUT.PUT_LINE(num2 || ' is greater than ' || num1);
ELSE
DBMS_OUTPUT.PUT_LINE('Both numbers are equal: ' || num1);
END IF;
END;
/
Explanation¶
- Java: Uses
doublefor numerical comparison withif-else if-else.Scannerreads the inputs. - Python: Uses
float()to convert input strings to floating-point numbers.if-elif-elsestructure directly compares the numbers. - C: Employs
scanf("%lf", ...)to readdoubleinputs. Compares numbers usingif-else if-elseand displays formatted output withprintf(). - Oracle: Implemented in PL/SQL. Uses
NUMBERdata type for numerical comparison withinIF-ELSIF-ELSEblocks. Substitution variables for interactive input.
Complexity Analysis¶
- Time Complexity: O(1) - A fixed number of comparisons are performed.
- Space Complexity: O(1) - A fixed number of variables are used.
Flowchart¶
graph TD
A[Start] --> B[Get num1]
B --> C[Get num2]
C --> D{num1 > num2?}
D -- Yes --> E[Display num1 is greater]
D -- No --> F{num2 > num1?}
F -- Yes --> G[Display num2 is greater]
F -- No --> H[Display Numbers are equal]
E --> I[End]
G --> I
H --> I
Sample Dry Run¶
| Step | num1 | num2 | num1 > num2? | num2 > num1? | Description |
|---|---|---|---|---|---|
| Input | 15 | 8 | - | - | User enters 15, 8 |
| Decision | 15 | 8 | True | - | 15 is greater than 8 |
| Output | - | - | - | - | Display "15 is greater than 8" |
| End | - | - | - | - | Program terminates |
| Input | 5 | 12 | - | - | User enters 5, 12 |
| Decision | 5 | 12 | False | - | 5 is not greater than 12 |
| Decision | 5 | 12 | - | True | 12 is greater than 5 |
| Output | - | - | - | - | Display "12 is greater than 5" |
| End | - | - | - | - | Program terminates |
| Input | 7 | 7 | - | - | User enters 7, 7 |
| Decision | 7 | 7 | False | - | 7 is not greater than 7 |
| Decision | 7 | 7 | - | False | 7 is not greater than 7 |
| Output | - | - | - | - | Display "Both numbers are equal: 7" |
| End | - | - | - | - | Program terminates |
Practice Problems¶
Easy¶
- Modify the program to find the smaller of two numbers.
- Find if two numbers are equal or not.
Medium¶
- Add input validation to ensure valid numerical input.
- Implement a program that compares two strings lexicographically.
Hard¶
- Compare two complex objects based on a specific attribute (e.g., two Person objects based on age).
"The computer does not care about your feelings, it only cares about your logic." - Anonymous