# algorithm to print the digits in the correct order

I've been trying to write an algorithm that will print separately the digits from an integer. I have to write it in Pseudocode. I know how to write an algorithm that reverse the digits.

``````digi(n):
while n != 0:
x = n % 10
n = n // 10
print (x)
``````

But I don't know how to write an algorithm to print the digits in the correct order. For example, the input is integer `123467` and the output is: `1 2 3 4 6 7`. The numbers will be input from the user, and we cannot convert them to a string. I need help getting started on writing algorithms.

• This question is "grandfathered". It was created and answered during the early years of Programmers Stack Exchange, where the allowed topics are more liberal and less focused. It will not be accepting new answers. Mar 2 at 20:16

`log n` will give you the number of (decimal) digits in `n`.

Notice that `1234 / (10^[4-1]) = 1.234` which rounds down to `1`. Repeat as necessary (`mod 10`) to print each digit.

• `1.234 -> 1`
• `12.34 % 10 -> 2.34 -> 2`
• `123.4 % 10 -> 3.4 -> 3`
• `1234 % 10 -> 4`
• You can use something similar to elegantly implement a radix sort for all possible bases.
– user28988
Oct 23, 2012 at 20:20
• The problem with this solution is to properly cover edge cases. Logarithm is floating-point number (which are tricky themselves), not to mention, 10-based logarithm is not natural (natural is e-based one), so some more error can accumulate. Which can leads to situations, where `log n` will be off by one. So you should not blindly believe it, but test the edge case. Also, if you know you have an integer, it is safer (again, floating point, unsafe edge cases) to do things like `(1234 - 1234 % (10 ^ [4-1])/(10 ^ [4-1]))` to eschew the floating point. Oct 24, 2012 at 8:20
• There are no cases where "`log n` will be off by one", provided you do the research properly: en.wikipedia.org/wiki/Logarithm#Number_theory. Why is it necessarily safer to do purely integer operations? Can you give some examples? You have made a fair few of assertions (non-natural logs cause errors, `log n` is off by one, floats are bad) with nothing to back them up.
– Jay
Oct 24, 2012 at 19:40
• @Jay: I don't see how that chapter explains why would the approximation used to calculate `log(n)` have to be strictly biased towards higher values (it is unlikely to be so unprecise to give error more than 1 for 10<sup><i>n</i></sup> - 1 for n ≤ 32). Jan 16, 2013 at 8:15

Recursive method

``````function print_straightforward
if(N<10)
print N
else
print_straightforward(N/10);
print N%10
``````

If you already have an algorithm to print them in reverse put them in a stack and then print the stack which will reverse the order.

The usual algorithm is to write a recursive function which recurses with n/10 and then prints n%10. Extra credit for correctly handling negative numbers.