|
-
April 8th, 2013, 01:02 AM
#3
Re: Help with recursive function
 Originally Posted by Symus
-Write a recursive function that prints an integer with decimal separators. For example, 12345678 should be printed as 12,345,678.
An alternative to building a string is to split the integer numerically and print the parts separated by commas to standard output.
The standard way to strip off individual digits from a number is to use the % (modulo) operator followed by integer division. For a decimal number (base 10) it would look like this,
12345678 % 10 = 8
12345678 / 10 = 1234567
The number has effectively been split like this,
12345678 = 1234567*10 + 8
In this particular case you could instead split into 3-digit chunks,
12345678 % 1000 = 678
12345678 / 1000 = 12345
In the recursive function you decide what number is to be printed and if it's to be preceded by a comma. Then the function calls itself with the reduced number until 0 is reached. Finally when the recursion winds back the actual printing takes place according to the information gathered in each incarnation of the recursive function. In this process the number will be split from right to left and then printed with commas from left to right.
Phew, it's harder to describe than to code.
Last edited by nuzzle; April 8th, 2013 at 05:07 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|