
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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
- Find the Number of Unique Triplets Whose XOR is Zero using C++
- C++ Program to find out the sum of shortest cost paths for all given triplets
- All unique triplets that sum up to a given value in C++
- Count all triplets whose sum is equal to a perfect cube in C++
- Find N Unique Integers Sum up to Zero in C++
- Find all triplets in a sorted array that forms Geometric Progression in C++
- Find sum of sum of all sub-sequences in C++
- Print triplets with sum less than or equal to k in C Program
- 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
- Print all subarrays with 0 sum in C++
- Print all pairs with given sum in C++
Advertisements