How to count and print triplets from an array with sum smaller than a given value in C

1 Answer

0 votes
#include <stdio.h>

int main() {
    int array[] = { 4, 5, 2, 8, 1, 3, 8, 7, 10 };
    int size = sizeof(array) / sizeof(array[0]);
    int sum = 11;
    int count = 0;

    for (int i = 0; i < size - 2; i++) {
        for (int j = i + 1; j < size - 1; j++) {
            for (int k = j + 1; k < size; k++) {
                if (array[i] + array[j] + array[k] < sum) {
                    count++;
                    printf("%d: %d,%d,%d\n", count, array[i], array[j], array[k]);

                }
            }
        }
    }
    printf("Number of Triplets = %d", count);

    return 0;
}




/*
run:

1: 4,5,1
2: 4,2,1
3: 4,2,3
4: 4,1,3
5: 5,2,1
6: 5,2,3
7: 5,1,3
8: 2,1,3
9: 2,1,7
Number of Triplets = 9

*/

 



answered Sep 16, 2022 by avibootz
...