Here's the problem description:
“Write a recursive function that displays all the binary (base 2) numbers represented by a string of xs, 0s, and 1s. The xs represent digits that can be either 0 or 1. For example, the string 1x0x represents the numbers 1000, 1001, 110, 1101. The string xx1 represents 001, 011, 101, 111.”
Additional comments: The program has only two functions, main() and display(), but your display() may call other functions. The number will be no longer than 79 digits. Hint: Start with short strings, i.e., "0", "1", "x", "01", "00", "0x","1x", "xx", and reason out what would be necessary for them.
EXAMPLES
Binary number: 1xx01
10001
10101
11001
11101
Binary number: 11x0x11xx
110001100
110001101
110001110
110001111
110011100
110011101
110011110
110011111
111001100
111001101
111001110
111001111
111011100
111011101
111011110
111011111
Note: Your output does not need to have same order as above.
Attempt at solution: I've been spending a lot of time trying to figure recursion out. I've gotten closer, and my understanding of function stacks is getting better. I just get so lost with all the function calls. I try to visualize in my head what all the function calls are going to do once the recursion is over, but I can't keep track. Anyone have a good way to visualize this?
I spoke to my instructor about this. His clues were to travel from right to left, first placing 1s in all the x positions, then use function stacks to replace the previous x positions with 0s and 1s. Here's my work so far. I'm at a loss of how to make this thing work. Please help!
-Thanks
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> int display( char *string1, int size ); int main() { char string[80]; int i, size; printf("Binary number: "); fgets( string, 80, stdin); for ( i = 0 ; i < 80 ; i++ ) if ( string[i] == '\n' ) string[i] = '\0'; size = strlen( string ); display( string, size - 1 ); return(0); } int display( char *string, int i ) { if ( i == 0 ) { return 0; } if ( string[i] != 'x' ) { i -= 1; display( string, i ); return 0; } if ( string[i] == 'x' ) { string[i] = '0'; i -= 1; display( string, i ); printf("%s\n", string ); i += 1; string[i] = '1'; printf("%s\n", string ); return 0; } return(0); }