Im try to write a program that will decompose an integer...backwards.
essentially if a user inputs an integer like "1234", the output will be:
4,3,2,1.
Help?
thanks
Im try to write a program that will decompose an integer...backwards.
essentially if a user inputs an integer like "1234", the output will be:
4,3,2,1.
Help?
thanks
A couple of options:
1. Read the "integer" in as a string, check each character with isdigit(), and then reverse the string. This will allow "integers" of arbitrary length.
2. Read it into an integer variable, print it to a string with sprintf(), then reverse the string. This will limit you to the actual range of the integer type that you choose.
What can this strange device be?
When I touch it, it gives forth a sound
It's got wires that vibrate and give music
What can this thing be that I found?
Look into the modulus operator.
There's at least a 3rd option:
If you choose not to use recursion, because there is a problem here if the integer (at the first call of the function) is 0--since it won't output anything, you can still change this over to a while loop and avoid having to create a special case for 0. The other issue is with negatives... Not sure if that's an issue here, but you could take the absolute value of the number still, and set a flag if the number is x < 0.Code:#include <stdio.h> void print_digits(int x) { if (x > 0) { putc((x % 10) + '0', stdout); print_digits(x / 10); } } int main(void) { int x = 1234; print_digits(x); return 0; }
The only issue here is with datatype limitations, that wouldn't exist if you were to just avoid integers and deal with strings.
Last edited by cstryx; 07-17-2015 at 10:38 PM.
Read in an integer
As stated above, use the modulus function to get the *last* digit
A simple WHILE loop will suffice, recursion overkill
Definition: Politics -- Latin, from
poly meaning many and
tics meaning blood sucking parasites
-- Tom Smothers