Find two smallest elements in an array
C program to find two smallest elements in a one dimensional array.
Program
#include<stdio.h>
#include<conio.h>
#include<limits.h>
#define MAX 50
void main()
{
int arr[MAX];
int i, n, min, second, flag;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&arr[i]);
}
min = arr[0];
second = INT_MAX;
flag = 0;
for(i=0;i<n;i++)
{
if(arr[i] < min)
{
second = min;
min = arr[i];
flag = 1;
}
else if(arr[i] < second && arr[i] != min)
{
second = arr[i];
flag = 1;
}
}
if(flag == 0)
{
printf("\nSmallest element of the array is\t:%d",min);
printf("\nSecond Smallest element does not exist");
}
else
{
printf("\nSmallest element of the array is\t:%d",min);
printf("\nSecond smallest element of the array is\t:%d",second);
}
getch();
}
Output
********** Run1 **********
Enter the number of elements in the array :8
Enter the elements
Element 1 :45
Element 2 :41
Element 3 :5
Element 4 :45
Element 5 :21
Element 6 :58
Element 7 :56
Element 8 :56
Smallest element of the array is :5
Second smallest element of the array is :21
********** Run2 **********
Enter the number of elements in the array :4
Enter the elements
Element 1 :52
Element 2 :52
Element 3 :52
Element 4 :52
Smallest element of the array is :52
Second Smallest element does not exist