Triplet that sum to a given value in C

Triplet that sum to a given value

 

Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false. 

Input: array = {1, 2, 3, 4, 5}, sum = 9

Output: 5, 3, 1

Explanation: There is a triplet (5, 3 and 1) present in the array whose sum is 9.

triplet that sum to a given value

Algorithm :

  • Take  size of the array from the user and store it in a variable say n.
  • Now take n elements of the array from the user.
  • Take one more interger value o
  • Create three nested loop first loop runs from start to end (loop counter i), the second loop runs from i+1 to end (loop counter j) and the third loop runs from j+1 to end (loop counter k)
  • The counter of these loops represents the index of 3 elements of the triplets.
  • Find the sum of the ith, jth and kth element. If the sum is equal to a given sum. Print the triplet and break.
  • If there is no triplet, then print “No triplet exists”.
triplet that sum to a given value in C

Code in C program based on above Algorithm

#include<stdio.h>

int main()
{
int n;

printf("Enter the size of the array : ");
scanf("%d", &n);

int a[n];

printf("\nEnter the %d elements :", n);
for(int i=0; i<n; i++){
scanf("%d", &a[i]);
}

int s;
printf("\nEnter the required sum :");
scanf("%d", &s);

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(a[i]+a[j]+a[k]==s){

printf("%d %d %d", a[i], a[j], a[k]);
return 0;
}
}
}

}

printf("No triplet exists");

return 0;
}
Output :

Enter the size of the array : 5

Enter the 5 elements : 1 3 5 11 8

Enter the required sum : 15

1 3 11