Q:

C program to find two elements whose sum is closest to zero

0

C program to find two elements whose sum is closest to zero

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will create an array of integers and find two elements whose sum is closest to zero and print them on the console screen.

Program:

The source code to find two elements whose sum is closest to zero is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to find two elements
// whose sum is closest to zero

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    int arr[] = { 62, 35, -15, 20, -10, 35 };
    int count = 0;

    int i = 0;
    int j = 0;

    int msum = 0;
    int sum = 0;
    int min1 = 0;
    int min2 = 0;

    min1 = 0;
    min2 = 1;
    msum = arr[0] + arr[1];

    for (i = 0; i < 5; i++) {
        for (j = i + 1; j < 5; j++) {
            sum = arr[i] + arr[j];
            if (abs(msum) > abs(sum)) {
                msum = sum;
                min1 = i;
                min2 = j;
            }
        }
    }

    printf("Elements their sum is closest to 0 are %d, %d\n", arr[min1], arr[min2]);
    return 0;
}

Output:

Elements their sum is closest to 0 are -15, 20

Explanation:

Here, we created an array arr with 6 elements. Then we used loops to find the sum of two elements their sum is closest to 0 and print those elements on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to check a given number appears more tha... >>
<< C program to print the square of array elements...