Site icon Study Algorithms

Generate All Strings of ‘n’ bits. Assume A[0….n-1] be an array of size n.

void binary(int n)
{
    if(n < 1)
        printf("%s\n",A);    // Assume A is a global variable
    else
    {
        A[n-1] = '0';
        binary(n-1);
        A[n-1] = '1';
        binary(n-1);
    }
}

So if you supply n = 4 in the function what you get as the output is this.

0000
1000
0100
1100
0010
1010
0110
1110
0001
1001
0101
1101
0011
1011
0111
1111

You can download the code here.

Exit mobile version