Search code examples
carraysmaxminfunction-definition

How do I print the index of the maximum and minimum values?


The following code prints the maximum and minimum value. How do I go about printing the index of those values rather than the values themselves?

#include <stdio.h>

int main()
{
    int arr1[100];
    int i, mx, mn, n;   

       printf("Input the number of elements to be stored in the array :");
       scanf("%d",&n);

       printf("Input %d elements in the array :\n",n);
       for(i=0;i<n;i++)
            {
          printf("element - %d : ",i);
          scanf("%d",&arr1[i]);
        }


    mx = arr1[0];
    mn = arr1[0];

    for(i=1; i<n; i++)
    {
        if(arr1[i]>mx)
        {
            mx = arr1[i];
        }


        if(arr1[i]<mn)
        {
            mn = arr1[i];
        }
    }
    printf("Maximum element is : %d\n", mx);
    printf("Minimum element is : %d\n\n", mn);

    return 0;
}

Solution

  • Simply save the index when you're updating mx respectively mn:

    int max_index = 0;
    int min_index = 0;
    
    // ...
    
        if(arr1[i]>mx)
        {
            mx = arr1[i];
            max_index = i;
        }
    
    
        if(arr1[i]<mn)
        {
            mn = arr1[i];
            min_index = i;
        }