You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level1 programs for (beginner)
Example 1 in java>
arr = { 1, 3, 2, 4, 3, 5};
Pair with sum = 6 are 3,3 ,, 1,5 ,, 2,4
Program/ example to
Find pair of given sum in java>
//Find pair of given sum
public class FindPairOfGivenNumer {
public static void main(String args[]) {
int[] arr = { 1, 3, 2, 4, 3, 5};
int sum = 6; //3,3 ,, 1,5 ,, 2,4
findPairOfGivenSum(arr, sum);
}
public static void findPairOfGivenSum(int[] arr, int sum) {
int pairCount = 0;
System.out.println("Pairs= ");
// Consider all possible pairs and check their sums
for (int i = 0; i < arr.length; i++)
for (int j = i + 1; j < arr.length; j++)
if ((arr[i] + arr[j]) == sum){
System.out.println(arr[i] +" "+ arr[j]);
pairCount++;
}
System.out.printf("count = " + pairCount);
}
}
//output
/*
Pairs=
1 5
3 3
2 4
count = 3
*/
|
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
Related >
Labels:
Core Java
Level1 programs (beginners)