Doubt related to Two Pointer Approach - Pair Sum Problem

Is it necessary to define the elements of sorted array in the code itself? Can’t we provide the inputs from console?
When I am trying to write the code for that , it’s not working. Please let me know, where am I going wrong?

#include
using namespace std;
int main()
{

int n;
cin>>n;
int a[1000];
for(int i=0;i<n;i++)
{
	cin>>a[i];
}
int s;
cin>>s;

int i=0;
int j=sizeof(a)/sizeof(int)-1;

while(i<j)
{
	int c_sum=a[i]+a[j];
	if(c_sum>s)
	{
		j--;
	}
	else if(c_sum<s)
	{
		i++;
	}
	else if(c_sum==s)
	{
		cout<<a[i]<<" and"<<a[j]<<endl;
		i++;
		j--;
	}
}
return 0;

}

hi @distyb04
here j would be n-1 and not int j=sizeof(a)/sizeof(int)-1;
as u have allocated space for 1000 elements but storing only n elements…
so just make j = n-1, ur code will work fine…

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.