0% found this document useful (0 votes)
36 views

Triplet Sum

The document contains code to find all triplets in an array that sum to a given number x. It takes an input array arr, size of the array size, and the target sum x. It sorts the array and uses three nested for loops to iterate through all possible triplets, checking if their sum equals x and printing the triplet if it does.

Uploaded by

Yashika Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Triplet Sum

The document contains code to find all triplets in an array that sum to a given number x. It takes an input array arr, size of the array size, and the target sum x. It sorts the array and uses three nested for loops to iterate through all possible triplets, checking if their sum equals x and printing the triplet if it does.

Uploaded by

Yashika Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

// arr - input array

// size - size of array


// x - sum of triplets
#include<bits/stdc++.h>
using namespace std ;
void FindTriplet(int arr[], int size, int x) {
/* Don't write main().
* Don't read input, it is passed as function argument.
* Print output and don't return it.
* Taking input is handled automatically.
*/
int n = size;
//cin>>n;
sort(arr,arr+n) ;
for (int i=0;i<n-2;i++)
{
for(int j=i+1;j<n-1;j++)
{
for(int k=j+1;k<n;k++)
{
if((arr[i]+arr[j]+arr[k])==x)
{
/*if(arr[i]<arr[j])
{
if(arr[j]<arr[k])
cout<<arr[i]<<" "<<arr[j]<<" "<<arr[k]<<endl;
else if(arr[k]>arr[i])
cout<<arr[i]<<" "<<arr[k]<<" "<<arr[j]<<endl;
else
cout<<arr[k]<<" "<<arr[i]<<" "<<arr[j]<<endl;
}
else
{
if(arr[i]<arr[k])
cout<<arr[j]<<" "<<arr[i]<<" "<<arr[k]<<endl;
else if(arr[j]>arr[k])
cout<<arr[k]<<" "<<arr[j]<<" "<<arr[i]<<endl;
else

cout<<arr[j]<<" "<<arr[k]<<" "<<arr[i]<<endl;


}
}*/
cout<<arr[i]<<" "<<arr[j]<<" "<<arr[k]<<endl ;
}
}
}
}
}

You might also like