asad_hussain
asad_hussain

Reputation: 2011

Why is the output of this code blank

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

Answers (2)

nalzok
nalzok

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 jth bit of i. You can also write i & (1 << j) for the sake of readability.

Upvotes: 1

haccks
haccks

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

Related Questions