# Thread: finding the second maximum.

1. ## finding the second maximum.

I have created a program to read from an external file. The program must locate the first maximum and the second. I am unsure about how to find the second maximum. Possibly by resetting the first max, but I am unsure how to do it. Here is my code for the program to locate the first max. What should i do from here?
I am a big time beginner. Thanks!

Code:
```/* Homework 14 */

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define FILENAME "exam2.dat"

int main(void)
{

/* Declare and initalize variables. */
int j=0, locmax, flag0=0, x, max, count=0;
double sum=0.0, ave;
FILE*data;

/* Open file. */
data=fopen(FILENAME, "r");

while (fscanf(data, "%i", &x) == 1)

{
j++;
sum+=x;
count++;
if(flag0==0)
{
flag0=1;
max=x;
locmax=j;
}
if(x>max)
{
max=x;
locmax=j;
}
}
/* Compute average. */
{
ave=sum/count;

/* Print summary. */
printf("Average: %7.2f \n", ave);
printf("Maximum: %3i \n", max);
printf("Location of Max: %3i \n", locmax);
}
fclose(data);
return 0;
}```

2. Find it the same way you do the first one.
Code:
```max = 0; second = 0;
for each number
if a > max
second = max
max = a```
What part is confusing?

Quzah.

3. sorry i am confused. when i do this it prints out my max=0 and the location of both the first and the second max at the same location. how do i reset the max without making it 0 in the end

4. Just like I showed you. Initialize them to zero. Loop while you read your numbers, checking for updating each max as needed. Print them at the end.

Quzah.

5. Code:
```        {
max=0;
locscndmax=0;
if(x>max)
{
locscndmax=max;
locscndmax=j;
max=x;
}
}
}```
okay this is what i did but now it is printing the minimum value and the location of the last max

6. Is that what you want, or not? If not, why are you storing the location, instead of the actual value? I didn't do that. Do what I did, and if you want the location, store that also as another pair of values.

Quzah.

7. Alternatively if you are required to retrieve the n-th largest number - sorting is an option. Just sort and iterate through on the sorted list.