ARRAYS-TARGET SUM PAIRS--some test cases give wrong answer

link to ques: https://hack.codingblocks.com/contests/c/457/211

#include
#include <string.h>
using namespace std;

void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{ min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}

int main()
{
int n,c=0;
cin>>n;
int a[n],target;

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

cin>>target;

selectionSort(a,n);

for(int i=0;i<n-2;i++)
{
for(int j=i+1;j<n-1;j++)
{

	{
		if((a[i]+a[j])==target)
			cout<<a[i]<<" and "<<a[j]<<endl;
	}
}

}

return 0;
}

1 Like

Hy Shagun,
You have a slight error in the nested for loops of your code.
Refer the following code snippet

for(int i=0;i<n-1;i++)
{
 for(int j=i+1;j<n;j++)
  {
	if((a[i]+a[j])==target)
		cout<<a[i]<<" and "<<a[j]<<endl;
  }
}

You were using wrong condition in the loop , you were using i<n-2 that means you were stopping i at n-3 and you were using j<n-1 that means you were stopping j at n-2. That means you were not including the n-1th element inside any loop, that was the mistake. I have updated the code in the above snippet.
:slight_smile: