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.
/*
* C program to print all possible subsets
* with k element in each subset
*/
#include <stdio.h>
/* Function to generate subset */
void subset(int arr[], int data[], int start, int end, int index, int r)
{
int j, i;
if (index == r) {
for (j = 0; j < r; j++)
printf("%d ", data[j]);
printf("\n");
return;
}
for (i = start; i <= end && end - i + 1 >= r - index; i++)
{
data[index] = arr[i];
subset(arr, data, i+1, end, index+1, r);
}
}
/* End of subset() */
/* Function to print the subset */
void printsubset(int arr[], int n, int r)
{
int data[r];
subset(arr, data, 0, n - 1, 0, r);
}
/* End of printsubset() */
/* The main() begins */
int main()
{
int arr[20], k, n, i;
printf("Enter the number of input : ");
scanf("%d", &n);
printf("\nEnter the integers: \n");
for ( i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter value of k: ");
scanf("%d", &k);
printsubset(arr, n, k);
return 0;
}
$ 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]Related Posts:
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Practice Computer Science MCQs
- Apply for C Internship
- Check C Books