Saturday, June 19, 2021
Home coding Write a program to count pair with given sum?

Write a program to count pair with given sum?

Given a integer array, we have to find a program to calculate pair with given sum.and print the resultant value .

Example:

input:arr[]={1,5,7,-1,-5}
output:3

Logic:

step 1- traverse whole array and check pair of given sum.
step 2-print the desire result.

Code-

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int arr[]={1,5,7,-1,5};
    int n=sizeof(arr)/sizeof(arr[0]);
    int sum=6;
    int count=0;
   for(int i=0;i<n;i++)
   {
   for(int j=i+1;j<n;j++)
   {
       if(arr[i]+arr[j]==sum)
       {
           count++;
       }
   }
   }
   cout<<count<<endl;
   
   
    
    
}

Output:

3

Time complexity:0(N*N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments