Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find indexes of max numbers in array

i have a program in c that finds the first and second max in an array, but i want to get the indexes of these elements. Here is my code:

#include <stdio.h>
int main(){
    int max1,max2,n;
    scanf("%d",&n);
    int a[n],i;
    int i_m1,i_m2;
    i_m1 = i_m2=0;
    for(i = 0;i < n;i++){
        scanf("%d",&a[i]);
    }
    max1 = max2 = 0;
    for(i = 0;i < n;i++){
        if(a[i]>max1){
            max1=a[i];
            //i_m1++;
        } else if(a[i]>max2 && a[i]<max1){
            max2=a[i];
            //i_m2++;
        }
    }
    printf("%d %d\n",max1,max2);
    //printf("%d %d\n",i_m1,i_m2);
    for(i = 0;i < n;i++){
        printf("%d ",a[i]);
    }
    return 0;
}

I first enter the number of elements in the array then the array.
For example if i have an array

number of elements: 5
elements in array: 
3 4 2 5 1
indexes:
0 1 2 3 4
max1=5, max2=4
i_m1=3, i_m2=1

How can i get the indexes i_m1 and i_m2 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re thinking too hard about what to do with i as evidenced by the commented out i_m1++ and i_m2++.

If max1=a[i]; then it follows that i_m1 = i; and same for max2/i_m2.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading