Where does my code fail?

#include <bits/stdc++.h>

using namespace std;
int main() {
int n;
cin>>n;
int* ptr=new int[n];
for(int i=0;i<n;i++){
cin>>ptr[i];
}
sort(ptr,ptr+n);
int key;
cin>>key;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(ptr[i]+ptr[j]==key)
cout<<ptr[i]<<" and "<<ptr[j]<<endl;
}
}
delete [] ptr;
return 0;
}

Please explain me the exception case.

Hello Jaideep,
here is your working code- https://ide.codingblocks.com/s/171585
your code was correct.just a small bug was there. By pair they want both element of pair to be at different idices (i know it was not mentioned clearly) . but you were including cases where same element paired with itself .
example
if array is 1 ,2,3,4
and target is 4 then your code was counting (2+2 self pairing)
I hope you find this helpful
regards
Aman yadav

1 Like

Whoa! thanks for the crystal clear explanation:heart_eyes:

1 Like

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.

1 Like