Find two element in an array whose sum is closest to zero

The array is having both +ve and -ve values.Lets take array values as

 3 -7 8 9 5 -3

Then the two numbers with sum closest to zero will be 3 and -3.

Program :

# include <stdio.h>
# include <stdlib.h>
# include <math.h>
void sumclosetozero(int arr[], int size)
{
  int count = 0;
  int a, b, sum_min, sum, a_min, b_min;
  a_min = 0;
  b_min = 1;
  sum_min = arr[0] + arr[1];
  for(a = 0; a < size - 1; a++)
  {
    for(b = a+1; b < size; b++)
    {
      sum = arr[a] + arr[b];
      if(abs(sum_min) > abs(sum))
      {
        sum_min = sum;
        a_min = a;
        b_min = b;
      }
    }
  }

  printf(" The two elements whose sum is minimum are %d and %d",
          arr[a_min], arr[b_min]);
}


int main()
{
  int a[] = {3, -7, 8, 9, 5, -3};
  sumclosetozero(a, 6);
  getchar();
  return 0;
}

Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Programs and Puzzles in technical interviews i faced