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

C++Server Side ProgrammingProgramming

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.

    • Add the three elements.

    • 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.

raja
Published on 01-Feb-2021 12:06:02
Advertisements