How to find Second min and max value in C Array

C-Array

In this article, we are going to learn about how to find the Second maximum and minimum in an array. In this example, we are going to make use of the maximum and minimum elements and then switch to the second maximum and second minimum.

C program to find Second Min and Max value in Array of Numbers


#include<stdio.h>
int main()
{
   int arr[10], num, firstmax, secmax, firstmin, secmin;

   printf("Please enter the Size of array with Max size 10: ");
   scanf("%d",&num);

   printf("Please enter the elements in this Array: ");
   for(int i=0; i < num; i++)
      scanf("%d",&arr[i]);

   firstmax = firstmin = arr[0];

   
   for(int i=1; i < num; i++)
   {
     if(firstmax<arr[i]) 
          firstmax=arr[i];
     if(firstmin>arr[i]) 
          firstmin=arr[i];
   }

  
   secmax = firstmin;
   secmin = firstmax;


   for(int i=0; i < num; i++)
   {
     if(arr[i] < firstmax && arr[i] > secmax) 
           secmax = arr[i];
     if(arr[i] > firstmin && arr[i] < secmin) 
           secmin = arr[i];
   }



   printf("The maximum value element in Array is : %d",firstmax);
   printf("\nThe Second maximum value element in Array is : %d",secmax);
   printf("\nThe minimum value element in Array is : %d",firstmin);
   printf("\nThe Second minimum value element in Array is %d",secmin);

   return 0;
}

Output

Please enter the Size of array with Max size 10: 5
Please enter the elements in this Array: 12
13
14
15 20
The maximum value element in Array is : 20
The Second maximum value element in Array is : 15
The minimum value element in Array is : 12
The Second minimum value element in Array is 13