This is a C Program to implement binary counting method to generate subset of a set. This program generates all subsets of given set of numbers using binary counting method
Here is source code of the C Program to Implement the Binary Counting Method to Generate Subsets of a Set. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include<stdio.h>
#include<math.h>
int i, j;
int sequence[] = { 9, 3, 5, 6, 7 };
void binaryCounting(int N) {
int binary[(int) pow(2, N)];
for (i = 0; i < pow(2, N); i++) {
int b = 1;
binary[i] = 0;
int num = i;
while (num > 0) {
binary[i] += (num % 2) * b;
num /= 2;
b = b * 10;
}
}
printf("\nThe permutations are: ");
for (i = 0; i < pow(2, N); i++) {
printf("{ ");
for (j = 0; j < N; j++) {
if (binary[i] % 10 == 1)
printf("%d ", sequence[j]);
binary[i] /= 10;
}
printf("}\n");
}
}
int main(int argc, char **argv) {
printf("The elements in the set : ");
for (i = 0; i < 5; i++)
printf("%d ", sequence[i]);
for (i = 1; i < 5; i++) {
int j = i;
int temp = sequence[i];
while (j > 0 && temp < sequence[j - 1]) {
sequence[j] = sequence[j - 1];
j = j - 1;
}
sequence[j] = temp;
}
binaryCounting(5);
return 0;
}
Output:
$ gcc0 BinaryCounting.c $ ./a.out The elements in the set : 9 3 5 6 7 The permutations are: { } { 3 } { 5 } { 3 5 } { 6 } { 3 6 } { 5 6 } { 3 5 6 } { 7 } { 3 7 } { 5 7 } { 3 5 7 } { 6 7 } { 3 6 7 } { 5 6 7 } { 3 5 6 7 } { 9 } { 3 9 } { 5 9 } { 3 5 9 } { 6 9 } { 3 6 9 } { 5 6 9 } { 3 5 6 9 } { 7 9 } { 3 7 9 } { 5 7 9 } { 3 5 7 9 } { 6 7 9 } { 3 6 7 9 } { 5 6 7 9 } { 3 5 6 7 9 }
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice BCA MCQs
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Buy Computer Science Books
- Buy C Books