Java

Program to find second largest number among three numbers in Java3 min read

In this java tutorial. I will show you how to find the second number amoung three numbers with two alternative way.

Accept three numbers from the user and display the second largest number in java.




Way 1:

This code prompts the user to enter three integers and then finds the second largest number among them. Here is a brief explanation of how it works:

  1. The Scanner class is used to read input from the user.
  2. The program prompts the user to enter three integers, which are stored in variables num1, num2, and num3.
  3. The program checks which of the three numbers is the second largest. It does this by using a series of if-else statements that check various conditions.
  4. If one of the conditions is true, the program prints out the second largest number. If none of the conditions are true, the program prints out the third number, which is the smallest of the three.
  5. The program then ends.

Output:

Way 2:

This code prompts the user to enter three integers and then finds the second largest number among them. It does this by first finding the largest and smallest numbers, and then subtracting those two numbers from the sum of all three numbers. The result is the second largest number. Here is a brief explanation of how it works:

  1. The Scanner class is used to read input from the user.
  2. The program prompts the user to enter three integers, which are stored in variables num1, num2, and num3.
  3. The program uses a series of if-else statements to find the largest and smallest numbers. It does this by comparing the values of num1, num2, and num3 and setting the variables largest and smallest accordingly.
  4. The program then calculates the second largest number by subtracting the largest and smallest numbers from the sum of all three numbers.
  5. The program prints out the second largest number and then ends.

Output:

4 Comments

  • The program(the first way) does not work with values 5, 5, and 6. This is because 5 is not greater than 5, then the program moves to ‘else’ and prints 6 which is the wrong result. we can use relation operators(Specifically ‘ = ‘ instead is only ‘ ‘ ) to correct this and also shorten the program.

Leave a Comment