Check Largest of Four Numbers
This program finds the largest of four numbers using if-else ladder.
Problem Statement
Write a Java program that finds the largest of four numbers.
Source Code
| 1 | public class LargestFour { |
| 2 | public static void main(String[] args) { |
| 3 | int a = 12, b = 25, c = 18, d = 30; |
| 4 | if(a >= b && a >= c && a >= d) { |
| 5 | System.out.println("Largest: " + a + " - Eduinq"); |
| 6 | } else if(b >= a && b >= c && b >= d) { |
| 7 | System.out.println("Largest: " + b + " - Eduinq"); |
| 8 | } else if(c >= a && c >= b && c >= d) { |
| 9 | System.out.println("Largest: " + c + " - Eduinq"); |
| 10 | } else { |
| 11 | System.out.println("Largest: " + d + " - Eduinq"); |
| 12 | } |
| 13 | } |
| 14 | } |
Program Output
Largest: 30 - Eduinq
Explanation
The program compares four numbers using chained if-else conditions. Each block checks if one number is greater than or equal to the others. If true, it prints that number as the largest. If none of the first three conditions are true, the last else block prints the fourth number. This ensures all four numbers are compared systematically. It demonstrates how if-else ladders can handle multiple comparisons efficiently. Shows how if-else ladder can be extended to compare four values.