Write a program that inputs a series of 10 numbers and find the 2 largest values of the 10 numbers? (Only using if and loop)
Can anybody help me to solve the problem?. I tried to but it was not right. It cannot list out the second largest number. Any helps would be appreciated.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int counter = 0, number, largest = 0,largest2=0;
for (counter = 1; counter <= 10; counter++) {
printf("Enter number (%d): ", counter);
scanf_s("%d", &number);
if (number > largest)
{
largest = number;
}
else
{
if (number > largest2)
largest2 = number;
}
}
printf("The largest number is %d\n", largest);
printf("The second largest number is %d\n", largest2);
system("pause");
return 0;
}
When you get a new largest number, the old largest number become the second largest number. So all you need is a single check for the largest number, and two assignments.
Something like
if (number > largest)
{
largest2 = largest;
largest = number;
}
You still need to check for numbers larger than largest2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With