ARRAYS-TARGET SUM TRIPLETS
Take as input N, the size of array. Take N more inputs and store that in an array. Take as input “target”, a number. Write a function which prints all triplets of numbers which sum to target.
Input Format:
First line contains input N. Next N lines contains the elements of array and N+1 line contains target number.
Constraints:
Length of Array should be between 1 and 1000.
Output Format
Print all the triplet present in the array.
Sample Input
9
5
7
9
1
2
4
6
8
3
10
Sample Output
1, 2 and 7
1, 3 and 6
1, 4 and 5
2, 3 and 5
all the test cases are not correct. what is the reason?
my code is:
#include
#include
using namespace std;
int main() {
int n,target,a[1000];
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
cin>>target;
sort(a,a+n);
for(int j=0;j<n-2;j++){
int t=target-a[j];
int left=j;
int right=n-1;
do{
int sum= a[left]+a[right];
if(sum==t){
cout<<a[j]<<", "<<a[left]<<" and "<<a[right]<<endl;
left++;right--;
}
if(sum<t){
left++;
}
if(sum>t){
right--;
}
}while(left<right);
}
return 0;
}