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

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


// Write a program to find out second smallest element of an unsorted array
// Ex: [6,7,2,4,6,7,8] -> Second smallest: 4

#include
int main(){
     int len,min1,min2,i=0;
     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 smallest numbers of array
     min1 = array[0];
     min2 = array[1];
     for(i=1;i<len;i++){
            if(array[i]<min1){
                    min2 = min1;
                    min1 = array[i];                
            }
            else if(array[i]<min2){
                    min2 = array[i];          
            }
     }

    
// printing first and second smallest numbers
     printf("First smallest Element of an Array: %d\n",min1);
     printf("Second smallest Element of an Array: %d",min2);
}

No comments:

Post a Comment