Yair B. Yair B. - 9 months ago 47
C# Question

Convert decimal number to octal number in recourse ( C# )

I have an algorithm to convert number from decimal to octal, but the algorithm in while loop and I need to convert it to recursive function.
This is the algorithm in while loop:

int octalNumber = 0, i = 1;

while (x != 0)
octalNumber += (x % 8) * i;
x /= 8;
i *= 10;
return octalNumber;

Someone can help me to convert it to recursive function ?

Answer Source

This will do the job:

public int ToOctal(int x)
    if(x == 0)
        return 0;
    return x % 8 + 10 * ToOctal(x / 8);

Notice that in the recursive algorithm if x is equal to 0 we will stop the recursive call and return 0, while in your loop we will keep iterate until x will be zero, the two ways we will pass every x digit are logicaly the same

One more thing, while you have to use i variable to know what is the location of the the new digit, in the recursive algorithm we will not need this variable and instead we will use for this purpose the benefits of the recursive call stack.