Find two elements in array (smallest)

Write a program to find two elements in array such that difference between them is smallest.


Source Code:

#include<stdio.h>
#include<conio.h>
void main()
{
	int i,first,second,a[10],temp;
	clrscr();
	printf("Enter the array elements:");
	for(i=0;i<10;i++)
	{
		scanf("%d",&a[i]);
	}
	printf("\nArray elements:");
	for(i=0;i<10;i++)
	{
		printf("\n%d",a[i]);
	}
	first=a[0];
	temp=a[0];
	for(i=0;i<10;i++)
	{
		if(a[i]<first)
		{
			first=a[i];
		}
		if(a[i]>temp)
		{
			temp=a[i];
		}
	}
	second=temp;
	for(i=0;i<10;i++)
	{
		if(a[i]>first && second>a[i])
		{
			second=a[i];
		}
	}

	printf("\nThe two numbers are: %d and %d",first,second);
	getch();
}

Output:

Enter the array elements:
2
1
3
6
5
14
12
0
35
4

Array elements:
2
1
3
6
5
14
12
0
35
4

The two numbers are: 0 and 1

Leave a Reply

Your email address will not be published. Required fields are marked *