Find the largest of three numbers
Description: Write a method which gets three int numbers and returns the largest one. Test it with (12, 45, 30) and (7, 7, 3).
Hint:
- Use
ifwith&&, or callMath.max()two times.
Solution
public class Main {
static int largest(int a, int b, int c) {
if (a >= b && a >= c) return a;
if (b >= c) return b;
return c;
}
public static void main(String[] args) {
System.out.println(largest(12, 45, 30));
System.out.println(largest(7, 7, 3));
System.out.println(Math.max(12, Math.max(45, 30))); // shorter way
}
}
Output
45
7
45
How it works
- The first
ifchecks ifais at least as big as both others. - If not, the winner is
borc, so one more comparison is enough.
Read Java if else.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |