# Count Triplets such that one of the numbers can be written as sum of the other two in C++

C++Server Side ProgrammingProgramming

We are given an array Arr[] of integers with length n. The goal is to find the number of triplets (Arr[i],Arr[j],Arr[k]) such that the sum of any two numbers is equal to the third number.

a+b=c, where a,b,c are elements of Arr[] with indexes i,j,k such that 0<=i<j<k<n We will do this by using three for loops. Increment count if arr[x]+arr[y]=arr[z] and x!=y!=z. Let’s understand with examples.

## Input

arr[]= { 1,2,2,3,4 }, N=5

## Output

Number of triplets: 4

## Explanation

Triplets with arr[x]+arr[y]=arr[z].

Arr{}=[ 1,2,2,3,4 ] =(1,2,3) → 1+2=3
Arr{}=[ 1,2,2,3,4 ] =(1,2,3) → 1+2=3
Arr{}=[ 1,2,2,3,4 ] =(1,3,4) → 1+3=4
Arr{}=[ 1,2,2,3,4 ] =(2,2,4) → 2+2=4

Total triplets: 4

## Input

arr[]= {2,2,2,2,2}, N=5

## Output

Number of triplets: 0

## Explanation

Every two numbers have sum=4 which is not equal to third=2.

Total triplets: 0

## Approach used in the below program is as follows

• We take an integer array Arr[] initialized with random numbers.

• Variable N stores the length of Arr[].

• Function countTriplets(int arr[],int n) takes an array, its length returns the triplets in which one of the numbers can be written as sum of the other two

• Take the initial variable count as 0 for the number of triplets.

• Traverse array using three for loops for each element of the triplet.

• Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n.

• Check if arr[i]+arr[j]==arr[k] or arr[i]+arr[k]==arr[j] or arr[k]+arr[j]==arr[i] If true then increment count.

• At the end of all loops count will have a total number of triplets that meet the condition.

• Return the count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int countTriplets(int arr[], int n){
int count = 0;
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] || arr[j]+arr[k]==arr[i] || arr[k]+arr[i]==arr[j]){                   count++;
}
}
}
}
return count;
}
int main(){
int Arr[]={ 1,2,2,3,4 };
int N=5; //length of array
cout <<endl<< "Number of triplets : "<<countTriplets(Arr,N);
return 0;
}

## Output

Number of triplets : 4
Published on 29-Aug-2020 11:35:56