# Find a triplet that sum to a given value in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

In this tutorial, we are going to write a program that finds the triplet in the array whose sum is equal to the given number.

Let's see the steps to solve the problem.

• Create the array with dummy data.

• Write three inner loops for three elements which iterate until the end of the array.

• Compare the sum with the given number.

• If both are equal, then print the elements and break the loops.

## Example

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool findTriplet(int arr[], int arr_size, int sum) {
for (int i = 0; i < arr_size - 2; i++) {
for (int j = i + 1; j < arr_size - 1; j++) {
for (int k = j + 1; k < arr_size; k++) {
if (arr[i] + arr[j] + arr[k] == sum) {
cout << arr[i] << " " << arr[j] << " " << arr[k] << endl;
return true;
}
}
}
}
return false;
}
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
findTriplet(arr, 7, 12);
return 0;
}

## Output

If you execute the above program, then you will get the following result.

1 4 7

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on 01-Feb-2021 12:06:24