
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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.
#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.
- Related Articles
- JavaScript Program to Find all triplets with zero sum
- How to find all unique triplets that adds up to sum Zero using C#?
- Print all triplets with given sum in C++
- Find all triplets in a list with given sum in Python
- All unique triplets that sum up to a given value in C++
- C++ Program to find out the sum of shortest cost paths for all given triplets
- Find the Number of Unique Triplets Whose XOR is Zero using C++
- Count all triplets whose sum is equal to a perfect cube in C++
- Find all triplets in a sorted array that forms Geometric Progression in C++
- Print triplets with sum less than or equal to k in C Program
- Find N Unique Integers Sum up to Zero in C++
- Find all the pairs with given sum in a BST in C++
- Write a program in C++ to find the length of the largest subarray with zero sum
- Find sum of sum of all sub-sequences in C++
- Print all triplets in sorted array that form AP in C++

Advertisements