Write a program that finds two elements in an array of ineteger whose sum is closest to zero.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define NB_ELEMENT 10
void main()
{
int size;
int A[NB_ELEMENT];
int i, j;
int sum, min, pair1, pair2;
do{
printf("Enter the number of elements: ");
scanf("%d", &size);
}while(size<=1 || size > NB_ELEMENT); // we need at least 2 elements
for (i = 0; i < size ; i++) {
printf("Enter Element %d: ", i );
scanf("%d", &A[i]);
}
//consider the smallest pair, the first 2 elements
pair1 = A[0];
pair2 = A[1];
min = pair1 + pair2;
for(i = 0; i < size-1; i++)
for(j = i+1; j < size; j++)
{
sum = A[i] + A[j];
if(abs(sum) < abs(min))
{
min = sum;
pair1 = A[i];
pair2 = A[j];
}
}
printf("[%d %d] is the pair with minimum sum = %d.\n", pair1 ,pair2, min);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implementation of 3 stacks within a single array