Count pairs with a given sum
Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’.
Program:
public class pair_sum {
public static void main(String args[])
{
int a[]={3,4,2,6,5,2,1};
int n=a.length;
int sum=7;
for(int i=0;i<n-1;i++)
{
int first=a[i];
for(int j=i+1;i<n;j++)
{
int second=a[j];
if((first+second)==sum)
{
System.out.println("The pair of elemnets are"+first +" " +second);
}
}
}
}
}
OUTPUT:
The pair of elemnets are3 4
No comments:
Post a Comment