Print triplets with sum less than or equal to k in C Program


Given array with set of elements and the task is to find out set with exactly three elements having sum less than or equals to k.

Input − arr[]= {1,2,3,8,5,4}

Output − set -> {1, 2, 3} {1, 2, 5} {1, 2, 4} {1, 3, 5} {1, 3, 4} {1, 5, 4} {2, 3, 5} {2, 3, 4}

In this, first task is to calculate the size of array depending upon which for loop of i is iterated till size-2 and for loop of j is iterated till size-1 and for loop of k is iterated till size

Algorith

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

Example

#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}\n",arr[i], arr[j], arr[k] );
         }
      }
   }
   return 0;
}

Output

If we run above program then it will generate 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}
raja
Published on 08-Aug-2019 12:46:03
Advertisements