Sunday 1 September 2013

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



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

#include<stdio.h>
int main(){
  int a[50],size,i,j=0,small,secondsmall;
  printf("Enter the size of the array: ");
  scanf("%d",&size);
  printf("Enter %d elements in to the array: ", size);
  for(i=0;i<size;i++)
         scanf("%d",&a[i]);

  small=a[0];
  for(i=1;i<size;i++){
         if(small>a[i]){
               small=a[i];
               j = i;
      }
  }

  secondsmall=a[size-j-1];
  for(i=1;i<size;i++){
         if(secondsmall > a[i] && j != i)
              secondsmall =a[i];
  }

  printf("Second smallest: %d", secondsmall);
  return 0;
}

Output:
Enter the size of the array: 5
Enter 5 elements in to the array: 5 7 3 2 6
Second smallest: 3

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved