In this Java Program, we have to find the largest number of three given numbers.
For Example :Input : 5 3 9
Output : 9
Java Program to find maximum of three numbers using if else statement
Let A, B and C be three given numbers
- First compare A and B.
- If A > B, then print the maximum of A and C.
- Else If A < B, then print the maximum of B and C.
package com.tcc.java.programs; import java.util.Scanner; public class MaximumThreeNumbers { public static void main(String[] args) { int a, b, c, max; Scanner scanner; // Take three integer from user scanner = new Scanner(System.in); System.out.println("Enter Three Integer"); a = scanner.nextInt(); b = scanner.nextInt(); c = scanner.nextInt(); // Using if-else statement compare a, b and c if (a > b) { // compare a and c if (a > c) max = a; else max = c; } else { // compare b and c if (b > c) max = b; else max = c; } System.out.println("Largest Number : " + max); } }Output
Enter Three Integer 8 3 9 Largest Number : 9
Enter Three Integer -2 0 2 Largest Number : 2
Java Program to find maximum of three numbers using method
Let A, B and C be three given numbers and "getMax" be a function which takes two numbers as arguments and returns the maximum one.
- Find the maximum of A and B by calling getMax function. Let the maximum of A and B be X. (X = getMax(A, B));
- Now, compare X and C by calling getMax function and print the maximum of the two on screen.
- In this algorithm, we will call getMax function twice.
package com.tcc.java.programs; import java.util.Scanner; public class MaximumThreeNumbersFunction { public static void main(String[] args) { int a, b, c, max; Scanner scanner; // Take three integer from user scanner = new Scanner(System.in); System.out.println("Enter Three Integer"); a = scanner.nextInt(); b = scanner.nextInt(); c = scanner.nextInt(); max = getMax(getMax(a, b), c); System.out.println("Largest Number : " + max); } public static int getMax(int num1, int num2) { if (num1 > num2) { return num1; } else { return num2; } } }Output
Enter Three Integer 6 1 0 Largest Number : 6
Enter Three Integer 3 -8 2 Largest Number : 3
Recommended Posts