C/Display Reverse Number, no strings or arrays
Expert: Narendra - 12/6/2004
QuestionI'm learning C at my local university.
For homework assignment 3, I wrote a program that requests a
positive integer from the user, then replies,
"your number is ___"
"it has ___ digits"
"the reverse number is: ___"
with all the relevent information filled in and it works well.
The assignement is due next week.
The problem is: today I received an email saying I'm not allowed
to use an array or a string in writing the program!
I can't figure out how I can possibly get the reverse number to
the screen without using an array or a string.
(Only the reverse number is stumping me; both echoing the number
and giving the number of digits I can do)
Please tell me how I can do this.
AnswerIt is very easy.
Use an integer variable to store the reverse (say rev_num).
take out the first (rightmost) digit of the number.
Give it to rev_num.
Take out the 2nd digit from right.
Now multiply rev_num by 10 and add this new digit to it.
Do this till the last digit.
Here is an example:
number = 1234
rev_num = 0
last_digit = number - ((number / 10) * 10) = 4
rev_num = last_digit = 4
next_digit = (number / 10) - ((number / 100) * 10) = 3
rev_num = (rev_num * 10) + next_digit = (4 * 10) + 3 = 43
next_digit = (number / 100) - ((number /1000) * 100) = 2
rev_num = (rev_num * 10) + next digit = (43 * 10) + 2 = 432
next_digit = (number / 1000) - ((number / 10000) * 1000) = 1
rev_num = (rev_num * 10) + next_digit = (432 * 10) + 1 = 4321
So, you can see that rev_num now holds the reverse of the given number.
Just put this in a loop and use 10 as multiplication factor for achieving this.
Hope this helps.....
-Narendra