# finding the second maximum.

• 05-16-2009
lbillys
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");         /*Read file. */         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; }```
• 05-16-2009
quzah
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.
• 05-16-2009
lbillys
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
• 05-16-2009
quzah
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.
• 05-16-2009
lbillys
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
• 05-16-2009
quzah
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.
• 05-18-2009
0rion
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.