Reputation: 17
I just want to ask on why is there a need to write sum = sum*10+digit
instead of just sum = 0+digit
? since the result of sum*10
is just 0. This is a code in C language for reversing an entered number. Thanks!
#include <stdio.h>
int main()
{
int number, x = 0, digit, temporary, div = 10, sum = 0;
printf("Enter numbers\n");
scanf("%d", &number);
temporary = number;
START:
digit = number%div;
sum = sum*10+digit;
number = number/div;
if(number>0)
goto START;
printf("Reversed Number = %d\n", temporary);
printf("Reversed Number = %d\n", sum);
return 0;
}
Upvotes: 0
Views: 53
Reputation: 31306
In a situation like this it is a very good thing to examine what is happening with simple printouts. If you insert printf("sum: %d digit: %d number: %d\n", sum, digit, number);
before the if statement, it will become obvious what's going on.
$ ./a.out
Enter numbers
2345
sum: 5 digit: 5 number: 234
sum: 54 digit: 4 number: 23
sum: 543 digit: 3 number: 2
sum: 5432 digit: 2 number: 0
Reversed Number = 2345
Reversed Number = 5432
Sidenote: There are "approved" ways of using goto. This is not one of them. You should switch
START:
...
if(number>0)
goto START;
to
do {
...
} while(number>0)
Upvotes: 3