Online Snippets Library

Create C Program to find the second largest element of an array

To Findout largest and second largest element of array,We need to iterate array and check each element for largest and second largest element.Complete Program is given below.

C Program
#include <stdio.h>

int main() {
   int array[10] = {101, 56, 3, 777, 555, 69, 7, 8, 9, 0};
   int loop, largest, second;

   if(array[0] > array[1]) {
      largest = array[0];
      second  = array[1];
   }else {
      largest = array[1];
      second  = array[0];
   }

   for(loop = 2; loop < 10; loop++) {
      if( largest < array[loop] ) {
         second = largest;
         largest = array[loop];
      }else if( second < array[loop] ) {
         second =  array[loop];
      }
   }

   printf("Largest Element - %d \n Second Largest Element - %d \n", largest, second);   

   return 0;
}

Output

Largest Element - 777 Second Largest Element - 555