Print all pairs with given sum


Find all pairs of an integer array whose sum is equal to a given number

Solution:

//Java implementation of
// simple method to find
// print pairs with given sum.

class FindPairsN{

// Returns number of pairs
// in arr[0..n-1] with sum
// equal to 'sum'
static void getPairs(int arr[],
int n, int sum)
{
// int count = 0;

// Consider all possible pairs
// and check their sums
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
System.out.println("(" + arr[i] + ", " + arr[j] + ")");
}

// Main
public static void main(String[] arg)
{
int arr[] = { 1, 5, 7, -1, 5 };
int n = arr.length;
int sum = 6;
getPairs(arr, n, sum);
}
}

Comments

Popular posts from this blog

Priority Scheduling Algorithm Java Program.

Implement UNIX system calls like ps, fork, join, exec family, and wait for process management (use shell script/ Java/ C programming).

Implement a class CppArray which is identical to a one-dimensional C++ array (i.e., the index set is a set of consecutive integers starting at 0) except for the following : 1. It performs range checking. 2.It allows one to be assigned to another array through the use of assignment operator. 3.It supports a function that returns the size of the array.