Skip to main content

← Back to Overview

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

  1. Start.
  2. Get two numbers (num1, num2) from the user.
  3. If num1 is greater than num2: a. Display num1 as greater.
  4. Else if num2 is greater than num1: a. Display num2 as greater.
  5. Else (if num1 is equal to num2): a. Display that both numbers are equal.
  6. 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();
}
}

Explanation

  • Java: Uses double for numerical comparison with if-else if-else. Scanner reads the inputs.
  • Python: Uses float() to convert input strings to floating-point numbers. if-elif-else structure directly compares the numbers.
  • C: Employs scanf("%lf", ...) to read double inputs. Compares numbers using if-else if-else and displays formatted output with printf().
  • Oracle: Implemented in PL/SQL. Uses NUMBER data type for numerical comparison within IF-ELSIF-ELSE blocks. 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

Sample Dry Run

Stepnum1num2num1 > num2?num2 > num1?Description
Input158--User enters 15, 8
Decision158True-15 is greater than 8
Output----Display "15 is greater than 8"
End----Program terminates
Input512--User enters 5, 12
Decision512False-5 is not greater than 12
Decision512-True12 is greater than 5
Output----Display "12 is greater than 5"
End----Program terminates
Input77--User enters 7, 7
Decision77False-7 is not greater than 7
Decision77-False7 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

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir