Write a program to find out second largest element of an unsorted array

Write a program to find out second largest element of an unsorted array

// Write a program to find out second largest element of an unsorted array
// Ex: [5,73,7,3,5,7,8] -> Second largest: 8

#include
int main(){
     int len,max1,i=0,max2;
     printf("Enter length of an array:");
     scanf("%d",&len);                      // array length input from user
     int array[len];
    
     // user input for array elements
     printf("Enter Matrix1 Elements");
     for(i=0;i<len;i++){
             scanf("%d",&array[i]);
     }
 
     // first and second largest numbers of array
     max1 = array[0];
     max2 = array[1];
     for(i=1;i<len;i++){ if(array[i]>max1){
                    max2 = max1;
                    max1 = array[i];                
            }
            else if(array[i]>max2){
                    max2 = array[i];          
            }
     }
 
     // printing first and second largest numbers
     printf("First Largest Element of an Array: %d\n",max1);
     printf("Second largest Element of an Array: %d",max2);
}

No comments:

Post a Comment