This blog is under construction

Sunday 21 July 2013

C program to print subset of a set using recursion

Write a C program to print subset of a set using recursion.


  #include <stdio.h>
  #include <stdlib.h>
  #include <math.h>

  /* find subsets of a given set */
  void findSubsets(int *value, int n, int i) {
        int j;

        if (i < 0)
                return;

        printf("{");
        /*
         * To form subsets, we need to consider binary values
         * with "n" bits.  If n is 3, then the possible 
         * number of subsets is 2^3 = 8.  And we need to consider
         * binary values with 3 bits.(000, 001, 010, 011, 100,
         * 101, 110, 111)ie. decimal values 0 to 7.  Then form
         * the subsets using the above manipulated binary value.
         * If any of the bit(in binary value) is set, then note
         * the bit index.  Use the same index value to fetch the
         * value from the input array.  Suppose, 001 is the value.
         * Here, 0th bit is set.  So, the element at index 0
         * from input array needs to cosidered for subset outputs.
         */
        for (j = 0; j < n; j++) {
                /* 
                 * checking jth bit is set in i.  If
                 * it is set, then fetch the element at
                 * jth index in value array
                 */
                if (i & (1 << j)) {
                        printf("%d ", value[j]);
                }
        }
        printf("}\n");

        /* recursive call */
        findSubsets(value, n, i - 1);

        return;
  }

  int main() {
        int i, j, count, n, *value;

        /* get the number of inputs from user */
        printf("Enter the number of elements:");
        scanf("%d", &n);

        /* allocate memory to store the elements */
        value = (int *)malloc(sizeof(int) * n);

        /* get the elements from the user */
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ",i);
                scanf("%d", &value[i]);
        }

        /* 2^n - indicates the possible no of subsets */
        count = pow(2, n);

        /* finds the subsets of the given set */
        findSubsets(value, n, count - 1);

        return 0;
  }


Note:
gcc subset.c -lm => linked math library since we have used a math function pow().

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements:3
  Data[0]: 1
  Data[1]: 2
  Data[2]: 3
  {1 2 3 }
  {2 3 }
  {1 3 }
  {3 }
  {1 2 }
  {2 }
  {1 }
  {}


No comments:

Post a Comment