I have this function: int triplet(int *array, int size, int K) { int i, j, k;
for(i = 0; i < size-2; i++) {
for (j = i+1; j < size-1; j++) {
for (k = j+1; k < size; k++) {
/* Check if the sum of current triplets
is equal to "K" */
if(array[i] + array[j] + array[k] == K) {
printf("Triplet Found : %d, %d, %d\n", array[i], array[j], array[k]);
return 1;
}
}
}
}
/* No triplet found whose sum is equal to K */
return 0;}
But it only shows 1 triplet from my array when triplets are way too more and how to count all shows triplets ? What is better, have this triplet in function or in the int main (void) ? Thanks for advice
Don't return
from the function in
if(array[i] + array[j] + array[k] == K) {
printf("Triplet Found : %d, %d, %d\n", array[i], array[j], array[k]);
return 1;
}
You can do instead something like this:
int triplet(int *array, int size, int K) {
int i, j, k;
int found = 0; /* triplets whose sum is equal to K */
for(i = 0; i < size-2; i++) {
for (j = i+1; j < size-1; j++) {
for (k = j+1; k < size; k++) {
if(array[i] + array[j] + array[k] == K) {
printf("Triplet Found : %d, %d, %d\n", array[i], array[j], array[k]);
found++;
}
}
}
}
return found;
}