Write a program to find the closest pair of numbers entered by the user. Closest
ID: 3795620 • Letter: W
Question
Write a program to find the closest pair of numbers entered by the user. Closest pair is the pair of numbers whose difference is minimum among all the pairs. Consider the following set as an example {8, 2, 17, 4, 25, 32, 20}. Closest pair in this set is 2 and 4 with difference of 2. All the other pairs have differences > 2. If you add 24 to this set to get {8, 2, 17, 4, 25, 32, 20, 24}, then closest pair is 24 and 25 with difference of 1. All the other pairs have differences > 1. If there is more than 1 pair with same difference, return the first one. Have a loop in your program to read the numbers and use - 1 to quit the loop. Use an array of size 50 to insert the numbers. Use input redirection to test your program. Sample output for this recitation using input redirection is as follows fox01> recitation5Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[50],len=0;
int i=0,j,temp,fst,scnd,diff;
while(1)
{
scanf("%d",&a[len]);
if(a[len]==-1)
{
break;
}
len++;
}
//printf("%d ",len);
diff=abs(a[0]-a[1]);
for(i=0;i<len;i++)
{
for(j=i+1;j<len;j++)
{
temp = abs(a[i]-a[j]);
if(temp<diff)
{
fst=i;
scnd=j;
diff=temp;
}
}
}
printf("Closest pair:%d and %d, Difference: %d ",a[fst],a[scnd],diff);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.