C Program to Generate Subsets with k Elements in each Subset

This C program generates subsets with k elements in each subset.

Here is the source code of the C program to display all subsets with k element in each subset. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to print all possible subsets 
  3.  * with k element in each subset
  4.  */
  5. #include <stdio.h>
  6.  
  7. /*  Function to generate subset  */
  8. void subset(int arr[], int data[], int start, int end, int index, int r)
  9. {
  10.     int j, i;
  11.     if (index == r) {
  12.         for (j = 0; j < r; j++)
  13.             printf("%d ", data[j]);
  14.         printf("\n");
  15.         return;
  16.     }
  17.     for (i = start; i <= end && end - i + 1 >= r - index; i++)
  18.     {
  19.         data[index] = arr[i];
  20.         subset(arr, data, i+1, end, index+1, r);
  21.     }
  22. }
  23. /*  End of subset()  */
  24.  
  25. /*  Function to print the subset  */ 
  26. void printsubset(int arr[], int n, int r)
  27. {
  28.     int data[r];
  29.     subset(arr, data, 0, n - 1, 0, r);
  30. }
  31. /*  End of printsubset()  */
  32.  
  33. /*  The main() begins  */
  34. int main()
  35. {
  36.     int arr[20], k, n, i;
  37.     printf("Enter the number of input : ");
  38.     scanf("%d", &n);
  39.     printf("\nEnter the integers: \n");
  40.     for (  i = 0; i < n; i++)
  41.     {
  42. 	scanf("%d", &arr[i]);
  43.     }
  44.     printf("Enter value of k: ");
  45.     scanf("%d", &k);
  46.     printsubset(arr, n, k);
  47.     return 0;
  48. }

$ gcc k_subset.c 
$ a.out
Enter the number of input : 5
 
Enter the integers: 
1 2 3 4 5
Enter value of k: 3
1 2 3 
1 2 4 
1 2 5 
1 3 4 
1 3 5 
1 4 5 
2 3 4 
2 3 5 
2 4 5 
3 4 5

Sanfoundry Global Education & Learning Series – 1000 C Algorithms.

advertisement
advertisement
If you wish to look at all C Algorithms and Solutions, go to C Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.