Objective
The objective of this program is to generate the power set of a given set.
A power set is the set of all subsets of a set, including the empty set
and the set itself. For example, for the set {1, 2}, the power set is
{{}, {1}, {2}, {1, 2}}.
Code
#include
#include
void printPowerSet(int set[], int set_size) {
unsigned int power_set_size = pow(2, set_size);
for (unsigned int i = 0; i < power_set_size; i++) {
printf("{ ");
for (int j = 0; j < set_size; j++) {
// Check if jth element is included in the current subset
if (i & (1 << j)) {
printf("%d ", set[j]);
}
}
printf("}\n");
}
}
int main() {
int set[] = {1, 2, 3}; // Example set
int set_size = sizeof(set) / sizeof(set[0]);
printf("Power Set of {1, 2, 3}:\n");
printPowerSet(set, set_size);
return 0;
}
Program Structure
The program consists of a function printPowerSet
that takes an
array and its size as arguments and prints all subsets. The main function
initializes a set and calls printPowerSet
to display the power set.
- printPowerSet: This function calculates the total number of subsets
(which is 2 raised to the power of the size of the set) and iterates through each
possible combination using bit manipulation to determine which elements are included. - main: The entry point of the program, where the example set is defined
and the function to print the power set is called.
How to Run the Program
- Ensure you have a C compiler installed (like GCC).
- Copy the code into a text editor and save it as
powerset.c
. - Open a terminal or command prompt.
- Navigate to the directory where
powerset.c
is saved. - Compile the program using the command:
gcc powerset.c -o powerset
- Run the compiled program with:
./powerset