The Program in C that print the second maximum out of three numbers is given below:
#include <stdio.h>
int main() {
int num1, num2, num3;
int max, second_max;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Enter the third number: ");
scanf("%d", &num3);
// Finding the maximum number
if (num1 >= num2 && num1 >= num3) {
max = num1;
} else if (num2 >= num1 && num2 >= num3) {
max = num2;
} else {
max = num3;
}
// Finding the second maximum number
if (num1 < max) {
if (num1 >= num2 && num1 >= num3) {
second_max = num1;
} else if (num2 >= num1 && num2 >= num3) {
second_max = num2;
} else {
second_max = num3;
}
} else {
if (num2 < max) {
if (num2 >= num1 && num2 >= num3) {
second_max = num2;
} else {
second_max = num3;
}
} else {
if (num3 < max) {
if (num3 >= num1 && num3 >= num2) {
second_max = num3;
}
}
}
}
printf("The second maximum number is: %d", second_max);
return 0;
}
Output:
Enter the first number: 25
Enter the second number: 01
Enter the third number: 23
The second maximum number is: 23
Pro-Tips💡
The program prompts the user to enter three numbers and then finds the maximum number by using an if-else statement.
After finding the max number, it uses another if-else statement to find the second maximum number.
The second maximum number is found by comparing each number with the maximum number, if the number is less than the max number and greater than the other two numbers, it is the second max number.
This program uses nested if-else statements to find the second maximum number, it can also be done by using the short logic like the previous example to find the max number,
but in this case the nested if-else is more readable and easy to understand.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.