#include
using namespace std;
void sumpair(int a[1000], int l, int r, int sum)
{
if(l>=r)
return;
while(l<r)
{
if((a[l]+a[r])==sum)
cout<<a[l]<<" and "<<a[r]<<endl;
else if((a[l]+a[r])<sum)
l++;
else
r–;
}
}
int main()
{
int a[1000], i, n, sum;
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
cin>>sum;
sumpair(a, 0, n-1, sum);
return 0;
}
I wrote this code for array sum pair but it is showing 3 and 2 for infinite times. What is the mistake in this code?
Target Array Sum Pair
This type of approach will only work on Sorted arrays. First you need to sort the array.
Even after sorting, it is showing 1 and 4 infinite times.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
Sir, my doubt is not cleared yet as it is still showing 1 and 4 multiple times.