Home Array Count the triplets in C

# Count the triplets in C

1436
0

Count the triplets in C

Problem statement: Given an Array of distinct integers, count all the triplets such that the sum of two elements equals the third element.

#include <stdio.h>

int countTriplet = 0;

void triplet(int a, int b, int c)
{
if (a + b == c)
{
printf("%d\t%d\t%d\n", a, b, c);
countTriplet++;
}
}

void combination(int arr[], int end)
{

for (int i = 0; i < end - 2; i++)
triplet(arr[i], arr[i + 1], arr[i + 2]);
}

void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void sort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}

void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%d\t", arr[i]);
}
printf("\n*******************\n");
}

int main()
{
int arr[] = {1, 2, 3, 5, 8, 13, 21};
int data[3];
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array is:");
printArray(arr, n);
sort(arr, n);
combination(arr, n);
if (!countTriplet)
printf("No triplet in array!");
return 0;
}
 \$ gcc triplet.c \$ ./a.out Array is:1 2 3 5 8 13 21 ******************* 1 2 3 2 3 5 3 5 8 5 8 13 8 13 21 \$ gcc triplet.c \$ ./a.out Array is:10 30 80 210 ******************* No triplet in array!\$

If you like the post Count the triplets in C, please share your feedback!

also see

Previous articlePrint Inversions in an array in C
Next articleSplit nodes of a linked list into two halves