Reputation: 2011
I am trying to print the power set of a string.
The code gets compiled successfully, but, when executed, nothing gets printed on the screen.
I am unable to understand the reason behind this.
Below is the code:
#include<stdio.h>
#include<string.h>
#include<math.h>
void main()
{
char s[]="abcd";
int i,j,k=1;
int y=strlen(s);
int z=pow(2,y);
for(i=0;i<z;i++)
{
k=1;
for(j=0;j<y;j++)
{
if(j & k)
printf(" %c",s[j]);
k=k<<1;
}
printf("\n");
}
}
Upvotes: 3
Views: 101
Reputation: 16117
This code works as you want:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "abcd";
int i,j;
int y = strlen(s);
int z = 1 << y;
for(i = 0; i < z; i++)
{
for(j = 0; j < y; j++)
{
if(i & 1 << j)
printf(" %c",s[j]);
}
putchar('\n');
}
return 0;
}
I admit that I've made extra changes in your code, which are irrelevant to your question.
What actually matters is i & 1 << j
. This checks the j
th bit of i
. You can also write i & (1 << j)
for the sake of readability.
Upvotes: 1
Reputation: 106092
j & k
always evaluates to 0
.
j = 0, k = 1 ==> j & K = 0
j = 1, k = 10 ==> j & K = 0
j = 10, k = 100 ==> j & K = 0
j = 11, k = 1000 ==> j & K = 0
Upvotes: 8