crecursiondynamic-programmingprocedural-programmingnumber-systems

Convert decimal number into binary using recursion in C


I had this code. Everything is fine with the code. The only thing is I am not getting why we are multiplying by 10 in last second line when the function convert() is being called recursively.

#include<stdio.h>
int convert(int);
int main()
{
    int dec,bin;
    printf("\n Enter the decimal no.:");
    scanf("%d",&dec);
    bin=convert(dec);
    printf("\n The binary equivalent is %d",bin);
    return 0;
}
int convert(int dec)
{
    if(dec==0)
     return 0;
    else
     return ((dec%2)+10 * convert(dec/2));
}

Someone help me. Thanks in advance.


Solution

  • You seem not to understand what is happening:
    Imagine you are converting the number 9 into binary digits, then you should get "1001", which you are (using your program).

    However, the "1001" (one zero zero one) is shown as 1001 (one thousand and one).

    Oh, maybe you don't understand that multiplying by ten and adding something is the way to append something at the end: if I ask to you append the digit 2 to the digit 3, you will do the following:

    3 * 10 + 2 = 32
    

    You are doing the same thing here (but the digits "pretend" to be binary digits).