Recursion to the rescue!

Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal.

Solution:

void putlong(unsigned long n)
{
    if( n<10)
    {
        putchar(n%10+'0');
    }
    else
    {
        putlong(n/10);
        putchar(n%10+'0');    
    
    }              
}    

For example: n=657

the recursive path of this function is 

657 -- print 7, 65 print 5, 6 print 6 and the print sequence is 657.

recursive function 的输出顺序就是先调用的后输出.

 

posted @ 2013-06-26 03:23  pgu2  阅读(161)  评论(0)    收藏  举报