# Count pairs with given sum in C++

C++Server Side ProgrammingProgramming

We are given an integer array and the task is to count the total number of pairs that can be formed using the given array values such that the sum of the pairs is equal to the given sum.

Input − int arr[] = {2, 8, 1, 5, 11}, sum = 10

Output − Count of pairs with given sum 13 is − 2

Explanation

 a1 a2 a1 + a2 2 8 10 2 1 3 2 5 7 2 11 13 8 1 9 8 5 13 8 11 19 1 5 6 1 11 12 5 11 16

Input − int arr[] = {2, 8, -1, 5, -11}, sum = 6

Output − Count of pairs with given sum 6 is − 1

Explanation

 a1 a2 a1 + a2 2 8 10 2 -1 1 2 5 7 2 -11 -9 8 -1 7 8 5 13 8 -11 -3 1 5 6 1 -11 -10 5 -11 -6

## Approach used in the below program is as follows

• Input an array of integer elements to form a pair and the integer value of sum.

• Calculate the size of an array pass the data to the function for further processing

• Create a temporary variable count to match the pairs with the given sum

• Start loop FOR from i to 0 till the size of an array

• Inside the loop, start another loop FOR from j to i+1 till the size of an array

• Inside the loops, set the temporary variable total as arr[i] + arr[j]

• Check IF total == sum then increment the count by 1

• Return the count

• Print the result

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//Count pairs with given sum
int Pair_Sum(int arr[], int size, int sum){
int count = 0;
for (int i=0; i<size; i++){
for (int j=i+1; j<size; j++){
int total = arr[i] + arr[j];
if (total == sum){
count++;
}
}
}
return count;
}
int main(){
int arr[] = {2, 6, 1, 7, 9, 8} ;
int sum = 9;
int size = sizeof(arr)/sizeof(arr[0]);
cout<<"Count of pairs with given sum "<<sum<<" is: "<<Pair_Sum(arr, size, sum);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of pairs with given sum 9 is: 2
Published on 31-Aug-2020 09:43:41