Find All Pairs in Array whose Sum is Equal to given number Using Java

In this tutorial, we will learn to write Java Program to find all pairs of integers in an array whose sum is equal to a given number. There are multiple ways to solve this problem in Java and We will in this article.

For Example

int[] arr = {2, 4, 7, 5, 9, 10};
int targetSum = 14;

Output

Pairs of integers whose sum is equal to 14:
4, 10
7, 7
5, 9

It means the sum of (2,10) and (4,8) give 12 as output.

Program 1: Brute force

In this program, we will see the Brute force method to solve our problem. Brute Force involves iterating over all pairs of integers in the array and checking if their sum is equal to the target sum.

public class Main {

    public static void findPairs(int[] arr, int targetSum) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i; j < arr.length; j++) {
                if (arr[i] + arr[j] == targetSum) {
                    System.out.println(arr[i] + ", " + arr[j]);
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {2, 4, 7, 5, 9, 10};
        int targetSum = 14;
        System.out.println("Pairs of integers whose sum is equal to " + targetSum + ":");
        findPairs(arr, targetSum);
    }
}

Output

Pairs of integers whose sum is equal to 14:
4, 10
7, 7
5, 9

Explanation

In above program have a static method called findPairs. It takes two parameters, an integer array arr, and an integer targetSum. In this method, we have two nested for loops to iterate over the array and find all pairs of integers in the array. Here we are comparing the sum of two array elements with the target element. If the result matches we print the pair of integers using the System.out.println() method.

Conclusion:

In this program, we have learned to write a Java program to print all pairs of the elements present in an array whose sum is equal to the given number.