Home > Article > Backend Development > In a C program, print out triples whose sum is less than or equal to k
Given an array containing a set of elements, the task is to find a set containing three elements whose sum is less than or equal to k.
Input strong>− arr[]= {1,2,3,8,5,4}
Output − Setting → {1, 2, 3} { 1, 2, 5} {1, 2, 4} {1, 3, 5} {1, 3, 4} {1, 5, 4} {2, 3, 5} {2, 3 , 4} p>
Here, the first task is to calculate the size of the array, depending on the for loop iteration of i up to size-2, the for loop iteration of j up to size-1, the for loop iteration of k to size-1
START Step 1 -> declare int variable sum to k (e.g. 10), i, j, k Step 2 -> declare and initialise size with array size using sizeof(arr)/sizeof(arr[0]) Step 3 -> Loop For i to 0 and i<size-2 and i++ Loop For j to i+1 and j<size-1 and j++ Loop For k to j+1 and k<size and k++ IF arr[i]+ arr[j] + arr[k] <= sum Print arr[i] and arr[j] and arr[k] End IF End Loop for End Loop For Step 4 -> End Loop For STOP
#include <stdio.h> int main(int argc, char const *argv[]) { int arr[] = {1, 2, 3, 8, 5, 4}; int sum = 10; int i, j, k; int size = sizeof(arr)/sizeof(arr[0]); for (i = 0; i < size-2; i++) { for (j = i+1; j < size-1; j++) { for (k = j+1; k < size; k++) { if( arr[i]+ arr[j] + arr[k] <= sum ) printf( "{%d, %d, %d}</p><p>",arr[i], arr[j], arr[k] ); } } } return 0; }
If we run the above program, it will generate the following output.
{1, 2, 3} {1, 2, 5} {1, 2, 4} {1, 3, 5} {1, 3, 4} {1, 5, 4} {2, 3, 5} {2, 3, 4}
The above is the detailed content of In a C program, print out triples whose sum is less than or equal to k. For more information, please follow other related articles on the PHP Chinese website!