If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To find the largest of three numbers in Java, you can use the if-else
statement to compare the numbers and determine the maximum value. Here's a Java program to find the largest of three numbers:
javaCopy code
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();
// Find the largest number using nested if-else
int largest;
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
System.out.println("The largest number is: " + largest);
scanner.close();
}
}
Example output:
yamlCopy code
Enter the first number: 20
Enter the second number: 35
Enter the third number: 10
The largest number is: 35
In the program above, we take three numbers as input from the user and store them in the variables num1
, num2
, and num3
. We then use the if-else
statement to compare the numbers and assign the largest value to the variable largest
. We use the logical &&
operator to combine conditions and find the maximum among the three numbers.
Remember that this program will find the largest number among the given three. If two or more numbers have the same maximum value, the program will only return one of them as the largest.
Comments: 0