Control Flow
Java Program to Find Largest of Three Numbers
A Java program to find the largest among three numbers.
Problem Description
Write a Java program to find the largest number among three given numbers.
Code
public class LargestNumber {
public static void main(String[] args) {
double n1 = -4.5, n2 = 3.9, n3 = 2.5;
if( n1 >= n2 && n1 >= n3)
System.out.println(n1 + " is the largest number.");
else if (n2 >= n1 && n2 >= n3)
System.out.println(n2 + " is the largest number.");
else
System.out.println(n3 + " is the largest number.");
}
}Output
3.9 is the largest number.Explanation
if-else if-elseLadder: Checks conditions sequentially.n1 >= n2 && n1 >= n3: Checks ifn1is greater than or equal to bothn2andn3.n2 >= n1 && n2 >= n3: Checks ifn2is greater than or equal to bothn1andn3.- If neither is true,
n3must be the largest.
Try Yourself
Test your logic with these challenges.
- Change Values: Set
n1 = 10,n2 = 20,n3 = 30and run the program. - Find Smallest: Modify the conditions to find the smallest of the three numbers.
- All Equal: What happens if
n1 = 5,n2 = 5,n3 = 5? Trace the code. - Four Numbers: Can you extend the logic to find the largest of four numbers?
- Brain Twister: Can you solve this using the ternary operator (
? :) in a single line?double largest = (n1 >= n2) ? ((n1 >= n3) ? n1 : n3) : ((n2 >= n3) ? n2 : n3);
