Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Find pairs in array with given sum

Find pairs in array with given sum

Write a program to find all the pairs in an array that sum to some number.

Example:

Input: 

arr = [2, 4, 6, 8, 10]
sum = 10

Output:

Pair found at index 0 and 3 (8 + 2)

or

Pair found at index 1 and 2 (4 + 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 :

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

class prepinsta {

    static void pairssum(int a[],
                        int sizeint 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[] = { 246810 };
        int size = a.length;
        int sum = 10;
        pairssum(a, size, sum);
    }
}


OUTPUT:

( 2, 8)

(4 , 6)