As "jamesdlin" noted in his comment, the GMan approach will work, however you will need to save it in the buffer in order to print it in the correct order (its algorithm will print "6 5 4 3 2 1" for input 123456). At this point, I would say that it would be much easier to use sprintf as the “therefromhere” suggested in his answer (unless this is of course the purpose of the algorithm class, of course).
In my opinion, the easiest way to do this is to use recursion, so you can print the numbers in the correct order without using buffers.
Recursive implementation is very simple:
void PrintfRecursivly(int number) { if (number < 0) { number *= -1; printf("- "); } if (number > 10) { PrintfRecursivly(number / 10); printf(" "); } printf("%d", number % 10); } int main() { int number = -78900456; PrintfRecursivly(number); return 0; }
Entrance:
-78900456
Exit:
- 7 8 9 0 0 4 5 6
EDIT : thanks to Steve Jessop, who suggested the correct algorithm for positive integers while I was away. I modified the above method to print correctly for all ints (positive and negative), without the last space.
Please note that we can avoid checking negative values in each recursion by performing the check only once (in the main function or anywhere), but I did not write it because we would lose more on clarity than on improving performance.
source share