Program to count pairs with given sum we check whether wo elements exist in a[] whose sum is exactly b.
- First we initialed a array with value.
- Declare a sum value a.
- Here We traverse the for loop with index i=0
- Now create one for loop inside another for loop whose index start from i+1.
- Inside if condition we add two for loop (a[i]+a[j]) whose sum is exactly equal to .
- Now print pair some value.
public class FindPairSumInArray {
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 6 };
int b = 5;
System.out.println("pair sum value are:- ");
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if ((a[i] + a[j]) == b) {
System.out.println(a[i] + " -- " + a[j]);
}
}
}
}
}
Output :-
pair sum value are:-
1 — 4
2 — 3