C program Write a recursive function that displays all the binary (base 2) numbe
ID: 3689807 • Letter: C
Question
C program
Write a recursive function that displays all the binary (base 2) numbers represented by a string of x s, 0 s, and 1 s. The x s represent digits that can be either 0 or 1 . For example, the string 1x0x represents the numbers 1000 , 1001 , 1100 , 1101 . The string xx1 represents 001 , 011 , 101 , 111 . Hint: Write a helper function replace_first_x that builds two strings based on its input argument. In one, the first x is replaced by a 0 , and in the other by a 1 . The set function is_element may be useful too.
Explanation / Answer
#include <stdio.h>
void replace_first_x(char num[], int size, int index){
if(index == size){
printf("%s ", num);
return;
}
else if(num[index] == '1' || num[index] == '0'){
replace_first_x(num, size, index + 1);
}
else if(num[index] == 'x'){
num[index] = '1';
replace_first_x(num, size, index + 1);
num[index] = '0';
replace_first_x(num, size, index + 1);
num[index] = 'x';
}
}
int main(){
replace_first_x("1x1x1", 5, 0);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.