Second largest and smallest number

I need to read numbers from a txt file and find the the number of numbers, max, min, average, sum, second largest, and second smallest number. I cant seem to find the second smallest and largest number and I've tried many different variations of loops. Here's what I have:

int random;
int counter = 0;
int sum = 0;
int minValue = 2000;
int maxValue = -1000;
int max2 = 0;
int min2;

cout << fixed << setprecision(1);

while (infile >> random)
{
counter++;
sum += random;

if (random > maxValue)
maxValue = random;

if (random < minValue)
minValue = random;


}

cout << "Number of numbers: " << setw(5) << counter << endl;
cout << "Sum of numbers: " << setw(11) << sum << endl;
cout << "Average of numbers: " << setw(6) << static_cast <double> (sum) / counter << endl;
cout << "Largest number: " << setw(9) << maxValue << endl;
cout << "Smallest number: " << setw(5) << minValue << endl;
Could you clarify what you want to do for "second largest" if, say, there are two equal largest. Or if, say, all numbers are the same (say, 10, 10, 10, 10). In the last case do you want the "second largest" to be "10" or "undefined"?

Your coding would be straightforward if you allow "largest" and "second largest" to be the same (deal with the first two numbers explicitly, then loop the rest with some 'if' conditions); however, if you require them to be different it will be much harder (and won't be possible if all numbers are the same).

You can do either ... but you need to make the decision.
Topic archived. No new replies allowed.