Header-C
Header-C

 

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

  1. Ensure you have a C compiler installed (like GCC).
  2. Copy the code into a text editor and save it as powerset.c.
  3. Open a terminal or command prompt.
  4. Navigate to the directory where powerset.c is saved.
  5. Compile the program using the command: gcc powerset.c -o powerset
  6. Run the compiled program with: ./powerset

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)