×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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

Here, we are going to learn how to find two elements whose sum is closest to zero in C programming language?
Submitted by Nidhi, on July 11, 2021

Problem statement

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.

Finding two elements whose sum is closest to zero

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

// 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.

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.