Given a list of numbers, find the pair whose sum is closest to zero.
For example:
If the input list is -1, 2, 1, -4
then, the possible pairs are
{-1,2} with sum = 1
{-1,1} with sum = 0
{-1,-4} with sum = -5
{2,1} with sum = 3
{2,-4} with sum = -2
{1,-4} with sum = -3
Among these, the one which is closest to zero is '0', so the values -1 and 1 is the expected pair.
Implementation:
For example:
If the input list is -1, 2, 1, -4
then, the possible pairs are
{-1,2} with sum = 1
{-1,1} with sum = 0
{-1,-4} with sum = -5
{2,1} with sum = 3
{2,-4} with sum = -2
{1,-4} with sum = -3
Among these, the one which is closest to zero is '0', so the values -1 and 1 is the expected pair.
Implementation:
#include <stdio.h> #include <stdlib.h> int main(void) { int *a,i,n,sum,min,imin,jmin,j; /* Get the number of elements of the array */ scanf("%d",&n); /* Dynamically allocate the memory block with size of n integers and store the starting address of allocated block in a */ a=(int*)malloc(sizeof(int)*n); /* Get the elements of the array */ for(i=0;i<n;i++) scanf("%d",(a+i)); /* If the size of the array is less than 2, print not possible to print two integers */ if(n<2) printf("Input atleast two numbers\n"); /* If the array has only two elements, then the two elements is the only pair possible, so print them */ else if(n==2) printf("The two numbers which has sum closest to zero are %d & %d",*(a+0),*(a+1)); /* If the size of the array is more than 2, keep track of two indices, whose sum is closest to zero */ else if(n>2) { min=*(a+0) + *(a+1); imin=0; jmin=1; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { sum=*(a+i) + *(a+j); /* If the result is a negative value, then greatest value will be nearest to zero Else if the result is a positive value, then smallest positive value will be nearest to zero */ /* Taking absolute for both positive and negative number will give the minimum value closest to zero */ if(abs(sum)<abs(min)) { min=sum; /* store the two indices in imin and jmin */ imin=i; jmin=j; } } } } /* Print the two elements of the indices imin & jmin */ printf("the two elements whose sum is closest to zero are %d & %d",*(a+imin),*(a+jmin)); return 0; }