Java Program to find greatest among three numbers using nested if else.
Objective
Write a Java program to find the largest among three numbers using nested if-else statements.
Algorithm / Approach
- Read three numbers into variables
x,y, andz. - First, use an outer
ifto check ifx > y. - If true, use an inner
ifto check ifx > z. If yes,Xis greatest; otherwiseZis greatest. - If the outer condition is false, check if
y > z. If yes,Yis greatest; otherwiseZis greatest. - Print the result.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter X: ");
int x = s.nextInt();
System.out.print("Enter Y: ");
int y = s.nextInt();
System.out.print("Enter Z: ");
int z = s.nextInt();
if(x>y) {
if(x>z) {
System.out.print("X is Greater");
}
else {
System.out.print("Z is Greater");
}
}
else {
if(y>z) {
System.out.print("Y is Greater");
}
else {
System.out.print("Z is Greater");
}
}
}
}
Expected Output
Enter X: 10 Enter Y: 18 Enter Z: 14 Y is Greater
Explanation of the Program
- This program avoids the logical AND operator by placing
ifstatements inside otherifstatements. - The outer block narrows down the maximum candidate to either
xory. - The inner blocks then compare that winning candidate against
zto find the absolute maximum. - This approach demonstrates how control flow can branch hierarchically.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Poor indentation, which makes it extremely hard to see which
elsebelongs to whichif.