Mar 12, 2015 at 3:49am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <stdio.h>
int main()
{
int n,count=0,reverse = 0;
printf("Enter a number to reverse\n" );
scanf("%d" , &n);
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
/*How this Works:
forexample for 194
0 x 10 = 0
0+4 = 4
194/10 = 19
4 x 10 = 40
40 + 19%10 = 49
19/10 = 1
49 x10 = 490
410 + 1%10 = 491
1/10 = 0
*/
}
printf("Reverse of entered number is = %d\n" , reverse);
return 0;
}
I am beginner, and i found this code on google,
that only give reverse output of number. I am
really impressed by how it works, this part;
1 2 3 4 5 6
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
Is it good maths or programming?
Last edited on Mar 12, 2015 at 3:52am UTC
Mar 12, 2015 at 4:02am UTC
Why exactly are you multiplying by 10?
Nevermind just realized that reverse is of type int and not string.
Can't you simply do
1 2 3 4 5
while (n)
{
reverse += n % 10 + '0' ;
n /= 10;
}
Last edited on Mar 12, 2015 at 4:04am UTC
Mar 12, 2015 at 4:14am UTC
You literally copy-pasted an explanation for how it works, only to ask how it works. What still confuses you?
@giblit: Not sure what adding the integer value of '0'
is supposed to do.
Last edited on Mar 12, 2015 at 4:14am UTC
Mar 12, 2015 at 4:24am UTC
@giblit
I know that "n=n/10" = "n /= 10;", i could do that to simplify, but my question is different.
btw your While loop doesn't make sense, and it won't work.
I have described that how it works, see comments
in code.
Last edited on Mar 12, 2015 at 4:24am UTC
Mar 12, 2015 at 4:27am UTC
giblit wrote:reverse += input % 10 + '0' ;
This blows my mind. I see it and alarm bells go off saying "that shouldn't compile", yet it does. Somehow you mastered the art of order of operations and implicit conversions in a way that I am too afraid to. I would have used parenthesis and an explicit cast...
Subscriber360 wrote:btw your While loop doesn't make sense, and it won't work.
It does -
http://ideone.com/ZcRpWw
Last edited on Mar 12, 2015 at 4:28am UTC
Mar 12, 2015 at 4:29am UTC
It's a combination of both. It takes advantage of integer division (programming) to re-arrange the digits (math).
Subscriber360 wrote:Good Morning Mr.giblit its C not C++ :)
Well, this is a C++ forum...
Last edited on Mar 12, 2015 at 4:30am UTC
Mar 12, 2015 at 4:33am UTC
@LB
Good Morning to u too Sir :). Thanks Alot!
Actually its 9:30a.m here.