Question: In C write a recursive function that, given a number N , generates all binary patterns of length N . For example, for N=3 ,
In C write a recursive function that, given a number N, generates all binary patterns of length N. For example, for N=3, it will output:
000 001 010 011 100 101 110 111
Likewise, if N were 4, the output will be 16 lines long, corresponding to the binary strings of length 4, in increasing order, starting with 0000 and ending with 1111.
This exercise is best done using recursion. In particular, to generate all binary patterns of length N, do the following. First, set the leftmost position to '0', and generate all binary patterns over the remaining N-1 positions. Next, set the leftmost position to '1', and again generate all binary patterns over the remaining N-1 positions.
-----------------------------------
My attempt is below. I thought after the first recursion call is done it would go back to when "N=1" and "i=2" and use that in the second call and so on, but I guess I'm not understanding recursion right. Any help is appreciated.
int binaryGen(int N, char stringArray[]); int i = 0; int main() { char stringArray[10]; binaryGen(3, stringArray);
} int binaryGen(int N, char stringArray[]) { if(N == 0) { printf("%c",stringArray[0]); printf("%c",stringArray[1]); printf("%c",stringArray[2]); printf(" "); return 0; }
stringArray[i] = '0'; i++; binaryGen(N-1,stringArray); //stuck binaryGen(N-1,stringArray[i] = '1'); }
Step by Step Solution
There are 3 Steps involved in it
Lets go through the steps needed to properly write a recursive function to generate all binary patte... View full answer
Get step-by-step solutions from verified subject matter experts
