Vamsi Pavan’s Place

When curiousity outbursts …..

print integer using putchar, in same order

October 6th, 2006 · No Comments · Algorithms

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′);
}

Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

Tags:

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment