Header Ads Widget

Find the number of pairs in the array whose sum is equal to a given target | Unthikable solutions

 Find the number of pairs in the array whose sum is equal to a given target :-

Given an array of integer and the target value , write a program to Find the number of pairs in the array whose sum is equal to a given target. 

Sample input:

1 5 4 2 6 3 0 7
6

Sample output:

3


Explanation:- (1,5) (4,2) (6,0) are the pairs whose sum is equal to the target 6 so total 3 pairs are there so output is 3 .


Find the number of pairs in the array whose sum is equal to a given target:-

The objective of the code is to Find the number of pairs in the array whose sum is equal to a given target.

C++ code:-
#include<bits/stdc++.h>
using namespace std;

// function for finding the pairs
int findpairs(int a[],int target,int n)
{
int count=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if((a[i]+a[j])==target)
count++;
}
}
return count;
}

int main()
{
int n,target;
cout<<"Enter the size of the array"<<endl;
cin>>n;
int a[n];
cout<<"Enter the elements of the array"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Enter the target value"<<endl;
cin>>target;
cout<<findpairs(a,target,n);
return 0;
}

Output:-
Enter the size of the array
8
Enter the elements of the array
1 5 4 2 6 3 0 7
Enter the target value
6
3

Wipro :-

Infytq :-

Key Points;-

Hackerrank:-


C-tutorial:-

See more:-