Count pairs with given sum in C++


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

a1a2a1 + a2
2810
213
257
21113
819
8513
81119
156
11112
51116

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

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

Explanation

a1a2a1 + a2
2810
2-11
257
2-11-9
8-17
8513
8-11-3
156
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

Updated on: 31-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements