Enter any integer number as an input which denotes the size of the array. After that add all the required integers in the array. Now we pick all all two possible pairs and compare their sum with the minumum possible sum closest to zero. Since sum can be negative so we use absolute function to get only positive result. Hence the two integers with sum closest to zero are output.
Here is the source code of the Java Program to Find Two Elements such that their Sum is Closest to Zero. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Sum_Zero
{
public static void main(String[] args)
{
int n, min1 = 0, min2 = 1, sum, minimum;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of elements you want:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the numbers:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
minimum=Math.abs(a[0] + a[1]);
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
sum = Math.abs(a[i] + a[j]);
if(sum < minimum)
{
min1 = i;
min2 = j;
minimum = sum;
}
}
}
System.out.println("Element 1:"+a[min1]);
System.out.println("Element 2:"+a[min2]);
}
}
Output:
$ javac Sum_Zero.java $ java Sum_Zero Enter the number of elements you want:5 Enter all the numbers: -2 -1 3 6 5 Element 1:-2 Element 2:3
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
- Check Java Books
- Check Programming Books
- Apply for Computer Science Internship
- Practice Information Technology MCQs
- Practice BCA MCQs