Find Pairs in Array with Given Sum in Java

Find pairs in array with given sum

Pairs in Array with Given Sum in Java

On this page, we will look into a coding question where we will learn how to Find Pairs in Array with Given Sum in Java Programing Language. There might be different approaches to solve this question, one you will find here. If your approach is a bit different post it in the comment section.

Example:
  • Input:
    arr = [ 5, 2, 3, 4, 1, 6, 7 ]

    sum = 7
  • Output:
    [ 5, 2 ]  [ 3, 4 ]  [ 1, 6 ]

Algorithm to find pairs in an array with a given sum

  • Start 
  • Initialize an array with the given input.
  •  traverse each element and check if there’s another number in the array which can be added to it to give sum.
  • print the pairs 
  • END 

Java code :

Run
// Java implementation to
// print pairs with given sum.

class Main
{
    static void pairssum(int a[], int size, int sum)
    {
        //traverse through the array to find pairs
        for (int i = 0; i < size; i++)
            for (int j = i + 1; j < size; j++)
                if (a[i] + a[j] == sum)
                    System.out.println("(" + a[i] + ", " + a[j] + ")");
    }

    // Driver Code
    public static void main(String[] arg)
    {
        int a[] = { 5, 2, 3, 4, 1, 6, 7 };
        int size = a.length;
        int sum = 7;
        pairssum(a, size, sum);
    }
}

Output:

[5,2] [3,4] [1,6]

Learn About Arrays in C

Click on the below button to learn about in C Programming Language

Learn Arrays in C

Learn Data Structures

Click on the below button to study more Data Structure

Learn Data Structures