Find all triplets with zero sum in C++


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 that iterate until the end of the array.

    • Add the three elements.

    • Compare the sum with 0.

    • 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;
void findTripletsWithSumZero(int arr[], int n){
   bool is_found = false;
   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] == 0) {
               cout << arr[i] << " " << arr[j] << " " << arr[k] << endl;
               is_found = true;
            }
         }
      }
   }
   if (is_found == false) {
      cout << "Triplets doesn't exist"<<endl;
   }
}
int main() {
   int arr[] = {0, 1, -1, 2, 2, -4, 3, 4};
   findTripletsWithSumZero(arr, 8);
   return 0;
}

Output

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

0 1 -1
0 -4 4
1 -4 3
2 2 -4

Conclusion

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

Updated on: 01-Feb-2021

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements