public class Largest {
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.");
}
}
When you run the program, the output will be:
3.9 is the largest number.
In the above program, three numbers -4.5
, 3.9
and 2.5
are stored in variables n1, n2 and n3 respectively.
Then, to find the largest, the following conditions are checked using if else statements
The greatest number can also be found using a nested if..else statement.
public class Largest {
public static void main(String[] args) {
double n1 = -4.5, n2 = 3.9, n3 = 5.5;
if(n1 >= n2) {
if(n1 >= n3)
System.out.println(n1 + " is the largest number.");
else
System.out.println(n3 + " is the largest number.");
} else {
if(n2 >= n3)
System.out.println(n2 + " is the largest number.");
else
System.out.println(n3 + " is the largest number.");
}
}
}
When you run the program, the output will be:
5.5 is the largest number.
In the above program, instead of checking for two conditions in a single if statement, we use nested if to find the greatest.
Then, to find the largest, the following conditions are checked using if else statements