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

CServer Side ProgrammingProgramming

<p style="">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.</p><p><strong>Input&nbsp;</strong>&minus; arr[]= {1,2,3,8,5,4}</p><p style=""><strong>Output&nbsp;</strong>&minus; set &rarr; {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><p>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</p><h2>Algorith</h2><pre class="result notranslate">START Step 1 -&gt; declare int variable sum to k (e.g. 10), i, j, k Step 2 -&gt; declare and initialise size with array size using sizeof(arr)/sizeof(arr[0]) Step 3 -&gt; Loop For i to 0 and i&lt;size-2 and i++ &nbsp; &nbsp;Loop For j to i+1 and j&lt;size-1 and j++ &nbsp; &nbsp; &nbsp; Loop For k to j+1 and k&lt;size and k++ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IF arr[i]+ arr[j] + arr[k] &lt;= sum &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Print arr[i] and arr[j] and arr[k] &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;End IF &nbsp; &nbsp; &nbsp; End Loop for &nbsp; &nbsp;End Loop For Step 4 -&gt; End Loop For STOP</pre><h2>Example</h2><pre class="result notranslate">#include &lt;stdio.h&gt; int main(int argc, char const *argv[]) { &nbsp; &nbsp;int arr[] = {1, 2, 3, 8, 5, 4}; &nbsp; &nbsp;int sum = 10; &nbsp; &nbsp;int i, j, k; &nbsp; &nbsp;int size = sizeof(arr)/sizeof(arr[0]); &nbsp; &nbsp;for (i = 0; i &lt; size-2; i++) { &nbsp; &nbsp; &nbsp; for (j = i+1; j &lt; size-1; j++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (k = j+1; k &lt; size; k++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( arr[i]+ arr[j] + arr[k] &lt;= sum ) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;printf( &quot;{%d, %d, %d} &quot;,arr[i], arr[j], arr[k] ); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><p>If we run the above program then it will generate the following output.</p><pre class="result notranslate">{1, 2, 3} {1, 2, 5} {1, 2, 4} {1, 3, 5} {1, 3, 4} {1, 5, 4} {2, 3, 5} {2, 3, 4}</pre>
raja
Updated on 01-Jul-2020 08:08:03

Advertisements