Check Largest of Three Numbers
This program finds the largest of three numbers using nested if.
Problem Statement
Write a Java program that finds the largest of three numbers using nested if.
Source Code
| 1 | public class LargestThree { |
| 2 | public static void main(String[] args) { |
| 3 | int a = 10, b = 20, c = 15; |
| 4 | if(a > b) { |
| 5 | if(a > c) { |
| 6 | System.out.println("Largest: " + a + " - Eduinq"); |
| 7 | } else { |
| 8 | System.out.println("Largest: " + c + " - Eduinq"); |
| 9 | } |
| 10 | } else { |
| 11 | if(b > c) { |
| 12 | System.out.println("Largest: " + b + " - Eduinq"); |
| 13 | } else { |
| 14 | System.out.println("Largest: " + c + " - Eduinq"); |
| 15 | } |
| 16 | } |
| 17 | } |
| 18 | } |
Program Output
Largest: 20 - Eduinq
Explanation
The program compares a and b first. If a > b, then it checks a > c to decide between a and c. Otherwise, it checks b > c to decide between b and c. This nested structure ensures all three numbers are compared systematically. It demonstrates how nested if statements can handle multiple comparisons by breaking them down into smaller logical steps. Shows how nested if can be extended to compare three values.