I have to write a recursive function in C to convert a number from decimal to binary.
This is the prototype we were given void dec_to_binary(int n)
.
My code:
void dec_to_binary(int n)
{
// base case: if the number is 0, return
if (n == 0)
{
return;
}
// recursive case: divide the number by 2 and call the function again
dec_to_binary(n / 2);
// print the remainder (which will be 0 or 1)
printf("%d", n % 2);
}
Why doesn't it work when n
is 0?
Your code does not print anything when it is zero because it returns immediately. Perhaps you could check if input is zero before calling the function, like this:
void dec_to_binary_recursive(int n)
{
// base case: if the number is 0, return
if (n == 0)
{
return;
}
// recursive case: divide the number by 2 and call the function again
dec_to_binary_recursive(n / 2);
// print the remainder (which will be 0 or 1)
printf("%d", n % 2);
}
void dec_to_binary(int n)
{
if (n == 0)
{
printf("%d", 0);
}
else
{
dec_to_binary_recursive(n);
}
}
Keep in mind that this does not support negative numbers, and there probably a better way
As noted above your current dec_to_binary
function immediately returns and does nothing when the input is 0.
You can solve the problem without adding a function,
by having 2 base cases for the recursion: for 0 and 1:
#include <stdio.h>
void dec_to_binary(int n)
{
if (n == 0)
{
printf("0");
return;
}
if (n == 1)
{
printf("1");
return;
}
dec_to_binary(n / 2);
printf("%d", n % 2);
}
int main()
{
dec_to_binary(0);
printf("\n");
dec_to_binary(1);
printf("\n");
dec_to_binary(2);
printf("\n");
dec_to_binary(7);
printf("\n");
}
Output:
0
1
10
111
It's possible to make an way that does not need an wrapper function or a second argument. works with negatives too
void dec_to_binary(int n) {
if ((unsigned int)n > 1)
dec_to_binary((unsigned int)n/2);
printf("%u", (unsigned int)n % 2);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.