C Question

Generate all binary strings of length n with k bits set.(need to write on C)

Please help me to solve this task:
Generate all binary strings of length n with k bits set.(need to write on C)
for example:

n=5
k=3
11100
00111
11010
01011
**01110
11001
10011
**01101
**10110
10101


** can't generate these permutations

Code:

#include <stdio.h>
#define N 10
int main (void)
{
int mas[N]={0},kst,m,n1,z,a,b;
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d",&kst);
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d",&n1);
for(m=0;m1;m++)
mas[m]=1;
for(m=0;m<kst;m++)
printf("%d",mas[m]);
printf("\n");
for(m=0;m<n1;m++){
for(z=0;z<(kst-1);z++)
if((mas[z]==1) && (mas[z+1]==0)){
a=mas[z];
mas[z]=mas[z+1];
mas[z+1]=a;
for(b=0;b<kst;b++)
printf("%d",mas[b]);
printf("\n");

}
}

return 0;
}

Answer

I have solved this problem earlier! please find my code below! I hope this will help you out.

#include<stdio.h>

int NumberOfBitsSet(int number)
{
    int BitsSet = 0;

    while(number != 0)
    {

        if(number & 0x01)
        {
            BitsSet++;
        }
        number = number >> 1;
    }

    return BitsSet;
}

void PrintNumberInBinary(int number, int NumBits)
{
    int val;
    val = 1 << NumBits; // here val is the maximum possible number of N bits with only MSB set

    while(val != 0)
    {
        if(number & val)
        {
            printf("1");
        }
        else
        {
            printf("0");
        }

        val = val >> 1;
    }
}

int main()
{
    int n,k,i;
    int max,min;
    printf("enter total number of bits and number of bits to be set:\n");
    scanf("%d %d", &n, &k);

    min = ((1 << k) - 1); //min possible values with k bits set
    max = (min << (n-k)); //max possible value with k bits set!
    //printf("%d %d", min, max);
    for(i=0; i<= max; i++)
    {
        if(!(i<min))
        {
            if(NumberOfBitsSet(i) == k)
            {
                PrintNumberInBinary(i, (n-1));
                printf("\n");
            }
        }
    }

    return 0;
}