print integer using putchar, in same order

Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal.
[The solution of taking % 10 and / 10, which gives us the decimal value in reverse order. This requires an array since we need to print it out in the correct order. The interviewer wasn’t too pleased and asked me to give a solution which didn’t need the array ]

When ever you need extra memory, there are two ways, allocate the memory explicitly or use recursion during which the memory will be allocated automatically.

void PrintNumber(int n){
if(n <= 0) return; int Rem = n%10, Rest = n/10; PrintNumber(Rest); putchar(Rem+'0'); }

Leave a Reply

Your email address will not be published. Required fields are marked *