Sunday, 22 February 2015

To print all possible binary strings of size 'n'. Where 'n' to be taken as input (recursive approach)

//author: Pranshul Rastogi
//occupation:Student
//nationality:Indian

//Problem:- To print all possible binary strings of size 'n'. Where 'n' to be taken as input

//here maximum value of n can be 1000, one can change according to his/her need.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>


char str[1000];//array that contains string
//binary(int) prints all possible binary strings of size given using recursion

void binary(int n)
{
    if(n<0)
        fprintf(stdout,"%s\n",str);
    else
    {
        str[n]='0';
        binary(n-1);
        str[n]='1';
        binary(n-1);
    }
}
   
int main()
{
    int n;
    fprintf(stdout,"Enter the value of n --> ");//take the value of n
    fscanf(stdin,"%d",&n);
    assert(n<1000);
    binary(n-1);
    return 0;
}



/*
Output:- Enter the value of n--> 2
00
10
01
11
//you can copy and paste it on your respective compiler but try to solve it by //yourself first. For any query, please leave comment!! Thank you .
//Hope you find it useful
*/

No comments:

Post a Comment