This is a C Program to find the two elements such that their sum is closest to zero.
This program finds the two elements such that their sum is closest to zero.
1. Initialize the array with some numbers.
2. Firstly add the first two elements of array and let it be the minimum sum.
3. Keeping this as default, try all the combinations in the array. Use for loops for doing this.
4. Find the minimum and print the output.
Here is source code of the C Program to find the two elements such that their sum is closest to zero. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Find the two Elements such that their Sum is Closest to Zero
*/
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
void minabsvaluepair(int array[], int array_size)
{
int count = 0;
int l, r, min_sum, sum, min_l, min_r;
/* Array should have at least two elements*/
if (array_size < 2)
{
printf("Invalid Input");
return;
}
/* Initialization of values */
min_l = 0;
min_r = 1;
min_sum = array[0] + array[1];
for (l = 0; l < array_size - 1; l++)
{
for (r = l + 1; r < array_size; r++)
{
sum = array[l] + array[r];
if (abs(min_sum) > abs(sum))
{
min_sum = sum;
min_l = l;
min_r = r;
}
}
}
printf(" The two elements whose sum is minimum are %d and %d", array[min_l], array[min_r]);
}
int main()
{
int array[] = {42, 15, -25, 30, -10, 35};
minabsvaluepair(array, 6);
getchar();
return 0;
}
1. Initialize the array named array[] with the random values.
2. Call the function minabsvaluepair and pass array and its size as parameters.
3. In the function definition receive the parameters through variables array[] and array_size.
4. If the array_size is less than 2, then print the output as “Invalid Input” and exit.
5. Initialize the variables min_l and min_r with 0 and 1 respectively.
6. Initialize the variable min_sum with the sum of 1st two elements of the array.
7. Using two for loops, compare all the combinations with this default sum.
8. If the minimum one exits, then change the values of variables min_l and min_r with this new array positions and exit.
9. Print the array values with the positions min_l and min_r as output and exit.
The two elements whose sum is minimum are 15 and -10
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Apply for C Internship
- Check C Books
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Apply for Computer Science Internship