Home > Back-end >  Hello...why this function doesnt work for n=0?
Hello...why this function doesnt work for n=0?

Time:12-27

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)

 
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);
}



CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

It's possible to make an way that does not need an wrapper function or a second argument. Does not work for negatives tough

void dec_to_binary(int n) {
    if (n > 1)
        dec_to_binary(n/2);
    printf("%d", n % 2);
}
  • Related