LearnFrenzy
Sign in Take a free test

Bitwise Operators · Bit Manipulation Programs · Question 7

Generate all subsets of a set using bitmasks in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Print every subset of {a, b, c} using the bits of a counter.

Solution
main.c
#include <stdio.h>

int main(void) {
    const char items[] = {'a', 'b', 'c'};
    int n = 3;
    for (unsigned mask = 0; mask < (1u << n); mask++) {
        printf("{");
        for (int i = 0; i < n; i++)
            if (mask & (1u << i))           /* bit i says: include item i */
                printf("%c", items[i]);
        printf("}%s", mask + 1 < (1u << n) ? " " : "\n");
    }
    return 0;
}

Output Verified by compiling and running

{} {a} {b} {ab} {c} {ac} {bc} {abc}

The numbers 0 to 2ⁿ − 1 contain every combination of n bits, and each bit decides whether one item is in the subset. This is the standard way to brute-force small sets in contests.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links