This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

can not perform recursion function correctly

hi: I want to use recursion function to transform a integer from binary form to ascii form. But the result is wrong.I don't why ,please help to analyse.

soure code:

void
binary_to_ascii(unsigned int value)
{

   unsigned int quotient;
   quotient = value/10;
   if(quotient !=0 )
       binary_to_ascii(quotient);
   putchar(value%10+'0');

}


int
main()
{
 while(1){
    binary_to_ascii(4267);
  }
}


I want to produce characters '4','2','6','7' in sequence. but the result is '4','4','4'. I don't know what is wrong with my code.

Parents
  • A recursive function requires a stack for storing the return values - check how large this stack must be for each iteration of a recursive function.

    It is trivial to rewrite a very large group of recursive functions into iterative functions. In this case, the trivial implementation will produce the characters in reverse order - but each iteration only needs one byte to store one character until they are ready to be emitted in the correct order.

    Recursion is a very useful concept. But it is best left for problems where the complexity of storing state information and making subdivision decisions gets very complex with a non-recursive method.

    Any linear recursive algorithm can be trivially rewritten as an iteration. Many branching recursive algorithms (tree walking for example) can be trivially rewritten with an explicit state queue. It's quite seldom that a iterative solution can't be implemented in an obvious way.

Reply
  • A recursive function requires a stack for storing the return values - check how large this stack must be for each iteration of a recursive function.

    It is trivial to rewrite a very large group of recursive functions into iterative functions. In this case, the trivial implementation will produce the characters in reverse order - but each iteration only needs one byte to store one character until they are ready to be emitted in the correct order.

    Recursion is a very useful concept. But it is best left for problems where the complexity of storing state information and making subdivision decisions gets very complex with a non-recursive method.

    Any linear recursive algorithm can be trivially rewritten as an iteration. Many branching recursive algorithms (tree walking for example) can be trivially rewritten with an explicit state queue. It's quite seldom that a iterative solution can't be implemented in an obvious way.

Children