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






C program to find the second smallest element in an 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;
}

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




8 comments:

coolbee said...

it wont give the desired result if array is 3 2 8 7 5 it will print 5 as the second smallest no. instead of 2 hence loop for secondsmall shud begin with 0 instead of 1

coolbee said...

*instead of 3

neel shah said...

it is better to sort elements and find whatever we want....(may increase complexity of prog(maybe n^2))

Varun Kuntal said...
This comment has been removed by the author.
Varun Kuntal said...

i made it using only 1 for loop, check it out (take array as input or declare it as you wish, already understood, i've declared)

#include
int main()
{
int a[]={5,2,1,0,7,8,-5,-8};
int i,p=a[0],n=a[0],s=a[0];
for(i=1;i<8;i++)
{
if(a[i]<n)
n=a[i];
if(s!=n)
{
p=s;
s=n;
}
}
printf("Second Largest Number is %d",p);
return 0;
}

Pankaj Aagjal said...

//crack this function if you can.(0 is considered as error, I mean you can't pass 0 from array)
#include

int secsmall(int a[], int size){
int s1 = a[0], s2, flg = 0, i;
if(size < 2)
return 0;
for(i = 1; i < size; i++){
if(flg){
if(a[i] < s1){
s2 = s1;
s1 = a[i];
}
if(a[i] < s2 && a[i] > s1){
s2 = a[i];
}
}
else{
if(a[i] < s1){
s2 = s1;
s1 = a[i];
flg = 1;
}
if(a[i] > s1){
s2 = a[i];
flg = 1;
}
}
}
if(flg)
return s2;
return 0;
}

main(){
int a[] = {3, 3, 3};
printf("%d\n", secsmall(a, 3));
}

nur alam said...

what about this input 4 50 2 60 30

sanny chauhan said...

Good post
Here is a link for C/C++ programs and pointer programs. This may be useful for you.

Second smallest element in unsorted array

C++ Programs