Arrays-target sum triplet

#include
using namespace std;
int main(){
int a[100];
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
int target;
cin>>target;
for (int step = 0; step < n - 1; ++step)
{
for (int i = 0; i < n - step - 1; ++i)
{
// To sort in descending order, change > to < in this line.
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}

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

}
code is showing run time error…
what other approach we can use?

It is similar to array target sum pair problem.
Step 1: First Sort the array.
Step 2: Fix an element at i. Then find the rest two elements that sum to target in the similar way you have done the array target sum pair.

Consider the sorted array: [1 2 3 4 5 6 7]
Initially

  • i points to first element
  • l points to the left of the remaining array ie. to i+1
  • r points to the right of remaining array ie. to the last element.
    for every i:
    if(arr[l]+arr[r]+arr[i]==target)
    print the possibility, l++, r–

if(arr[l]+arr[r]+arr[i]>target)
r–

if(arr[l]+arr[r]+arr[i]<target)
l++

continue these steps till (l<r) -->after that increment i by one position and repeat the same steps.

Check your code following this approach. If you are not able to find the mistake then save your code on ide.codingblocks.com and then share its link.


still showing error


still showing error

Check now.

it is still showing run time error…

In line 31 and 34, you have to use else if instead of else. Please dry run the code by yourself. You will know your mistakes and understand better.

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