Largest Of Three Numbers In Java Using If Else
Finding the largest among three numbers is a fundamental programming task, crucial for understanding conditional logic and basic comparisons. In this article, you will learn how to determine the largest number using different if-else statement approaches in Java.
Problem Statement
The core problem involves comparing three numerical values and identifying which one holds the highest value. This comparison needs to account for all possible scenarios where any of the three numbers could be the largest, or if multiple numbers are equal.
Example
Let's consider three numbers: num1 = 10, num2 = 25, and num3 = 15.
The expected output for this set of numbers would be 25, as it is the largest among the three.
Background & Knowledge Prerequisites
To understand the solutions presented, readers should have a basic understanding of:
- Java Variables: How to declare and initialize integer or floating-point variables.
- Input/Output (I/O): How to take input from the user using
Scanner. - Comparison Operators: Operators like
>,<,>=,<=,==. -
if-elseStatements: Basic syntax and flow of conditional logic. - Logical Operators: Specifically, the
&&(logical AND) operator.
Use Cases or Case Studies
Identifying the largest of a small set of numbers is a common building block in various applications:
- Data Validation: Ensuring an input value falls within a specific range compared to other limits.
- Simple Sorting Algorithms: As a sub-task in sorting three elements, though not a general-purpose sort.
- Game Development: Determining the highest score, the strongest player, or the best stat among a few options.
- Financial Applications: Finding the highest transaction amount, highest interest rate, or best performing asset in a small comparison.
- Temperature Monitoring: Identifying the peak temperature reading from three sensors over a period.
Solution Approaches
We will explore two common methods using if-else statements to find the largest of three numbers.
Approach 1: Using Nested if-else Statements
This approach uses a hierarchical structure of if-else conditions to compare the numbers sequentially.
- One-line summary: Compares the first number with the second, then the larger of those with the third, to find the ultimate largest.
// Largest of Three Numbers using Nested If-Else
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Declare variables to store the three numbers
int num1, num2, num3;
// Step 2: Create a Scanner object to get user input
Scanner scanner = new Scanner(System.in);
// Step 3: Prompt the user to enter the three numbers
System.out.print("Enter the first number: ");
num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
num3 = scanner.nextInt();
// Step 4: Determine the largest number using nested if-else statements
int largest;
if (num1 >= num2) {
if (num1 >= num3) {
largest = num1; // num1 is largest
} else {
largest = num3; // num3 is largest
}
} else { // num2 > num1
if (num2 >= num3) {
largest = num2; // num2 is largest
} else {
largest = num3; // num3 is largest
}
}
// Step 5: Print the largest number
System.out.println("The largest number is: " + largest);
// Step 6: Close the scanner to prevent resource leak
scanner.close();
}
}
- Sample output
Enter the first number: 10 Enter the second number: 25 Enter the third number: 15 The largest number is: 25
- Stepwise explanation
- The program declares three integer variables (
num1,num2,num3) to store the input. - A
Scannerobject is initialized to read input from the console. - The user is prompted to enter three numbers, which are then stored in the respective variables.
- The main
ifcondition checks ifnum1is greater than or equal tonum2.
- If
num1 >= num2is true, it meansnum1is a candidate for the largest. Inside this block, anotherifcondition checks ifnum1is also greater than or equal tonum3. - If
num1 >= num3is true, thennum1is the largest. - Otherwise (
num1 < num3),num3must be the largest (becausenum1was already greater than or equal tonum2, butnum3is greater thannum1). - If
num1 >= num2is false (meaningnum2is strictly greater thannum1), thennum2is a candidate for the largest. Inside thiselseblock, anotherifcondition checks ifnum2is greater than or equal tonum3. - If
num2 >= num3is true, thennum2is the largest. - Otherwise (
num2 < num3),num3must be the largest (becausenum2was already greater thannum1, butnum3is greater thannum2).
- Finally, the program prints the value stored in the
largestvariable. - The
Scannerresource is closed.
Approach 2: Using Logical AND (&&) Operator
This approach uses logical AND to combine multiple comparison conditions in a single if-else if-else chain, making the code more flat and sometimes easier to read.
- One-line summary: Each condition directly checks if a number is greater than or equal to both other numbers simultaneously.
// Largest of Three Numbers using Logical AND
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Declare variables to store the three numbers
int num1, num2, num3;
// Step 2: Create a Scanner object to get user input
Scanner scanner = new Scanner(System.in);
// Step 3: Prompt the user to enter the three numbers
System.out.print("Enter the first number: ");
num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
num3 = scanner.nextInt();
// Step 4: Determine the largest number using if-else if-else with logical AND
if (num1 >= num2 && num1 >= num3) {
System.out.println("The largest number is: " + num1);
} else if (num2 >= num1 && num2 >= num3) {
System.out.println("The largest number is: " + num2);
} else {
// If neither num1 nor num2 is the largest, num3 must be
System.out.println("The largest number is: " + num3);
}
// Step 5: Close the scanner to prevent resource leak
scanner.close();
}
}
- Sample output
Enter the first number: 10 Enter the second number: 25 Enter the third number: 15 The largest number is: 25
- Stepwise explanation
- Similar to the previous approach, variables are declared, and a
Scanneris used to get three integer inputs from the user. - The first
ifcondition checks ifnum1is greater than or equal to bothnum2ANDnum3.
- If
num1 >= num2 && num1 >= num3is true,num1is the largest, and it is printed.
- If the first
ifcondition is false, theelse ifcondition is evaluated. It checks ifnum2is greater than or equal to bothnum1ANDnum3.
- If
num2 >= num1 && num2 >= num3is true,num2is the largest, and it is printed.
- If both the
ifandelse ifconditions are false, it implicitly means thatnum3must be the largest among the three (sincenum1andnum2were not the largest), so theelseblock executes, printingnum3. - The
Scannerresource is closed.
Conclusion
Determining the largest of three numbers using if-else statements is a foundational exercise in programming conditional logic. Both nested if-else and if-else if-else with logical AND operators provide effective solutions. While nested if-else clarifies sequential comparisons, the logical AND approach often results in flatter, more concise code for this specific problem.
Summary
- Problem: Identify the highest value among three given numbers.
- Nested
if-else: Compares numbers in a hierarchical manner, suitable for understanding layered conditions. - Logical
AND(&&): Combines multiple conditions efficiently, leading to a more direct comparison approach. - Readability: Both methods are clear; the logical
ANDmethod often provides a more streamlined code for multiple simultaneous comparisons. - Practicality: These methods are fundamental for basic comparisons and decision-making in various programming scenarios.