ProAnswers.org

Print all subsets of a set

Given a set of n objects, print all the subsets (power set) of the set.

#include 

 

#define MAX_SIZE 600

int res_length, val = 0, *res;               

void subset(int [], int [], int, int, int);   

void print_list(int [], int);                

 

int main()

{

    int i, n, list[MAX_SIZE], result[MAX_SIZE];

    printf("enter the size of the set

");

    scanf("%d", &n);

    res = result;

    for(i = 0; i < n; i++) list[i] = i + 1;

    for(i = 0; i <= n; i++){

        res_length = i;

        subset(list, result, i, 0, n - 1);       

    }

    return 0;

}

 

void subset(int list[], int *result, int length, int first, int last){

    int i;

    if(length == 0){

        val++;

        printf("length is %d --- ", res_length);

        printf("%2d. ", val);

        print_list(res, res_length);

        return;

    }

    for(i = first; i <= last - length + 1; i++){

        *result = list[i];

        subset(list, ++result, length - 1, i + 1, last);

        result--;                               

    }                                           

}

 

void print_list(int result[], int length){

    int i;

    if(length == 0){

        printf("{}

");

        return;

    }

    if(length == 1){

        printf("{%d}

", *result);

        return;

    }

    printf("{");

    for(i = 0; i < length - 1; i++) printf("%d, ", result[i]);

    printf("%d", result[i]);

    printf("}

");

}