# Write a Program to find K-complementary pairs in a given array of integers [Java interview]

###### Write a Program to find K-complementary pairs in a given array of integers

If Arr is Given Array, then pair (i, j) is K-complementary if K = Arr[i] + Arr[j];

###### Java Program to find k-Complementary Pairs
``````
package com.codenuclear; public class KComplementaryPairs {

public static void main(String args[])
{
KComplementaryPairs obj = new KComplementaryPairs();
int[] array = {2,5,7,1,4,2};
int k = 6;
System.out.println("\nTotal K Complementary Pairs :- "+obj.findKComplementaryPairs(array, k));

}

public int findKComplementaryPairs(int[] array, int K)
{
int count = 0;
int arrLength = array.length;

for(int i = 0; i < arrLength; i++)
{
for (int j = i; j < arrLength; j++ )
{
if (array[ i ] + array[ j ] == K )
{

if ( i != j )
{
System.out.println("K-Complementary Pair :- ("+array[i]+" , "+array[j]+")");
System.out.println("K-Complementary Pair :- ("+array[j]+" , "+array[i]+")");
// Here count incremented by 2 when i!=j,
// the reason is K = Arr[i] + Arr[j] as well as K = Arr[j] + Arr[i], so we found two pairs (i,j) and (j,i).
count += 2;
}

else
{
System.out.println("K-Complementary Pair :- ("+array[i]+" , "+array[j]+")");
count++;
}
}
}
}

return count;
}

}
``````

Output K-Complementary Pair :- (2 , 4) K-Complementary Pair :- (4 , 2) K-Complementary Pair :- (5 , 1) K-Complementary Pair :- (1 , 5) K-Complementary Pair :- (4 , 2) K-Complementary Pair :- (2 , 4) Total K Complementary Pairs :- 6 