Following is the code for reducing a given number to a single digit by adding the digits of the number recursively.
For example if the input is 845
the output is 8
. 8+4+5 = 17 -> 1+7 = 8
(output)
#include <stdio.h>
#define TRUE 1
int reduceToSingle(int numb);
int main()
{
int numb;
scanf("%d",&numb);
printf("Original = %d Single digit = %d\n", numb, reduceToSingle(numb));
return TRUE;
}
int reduceToSingle(int numb)
{
int sum = 0, digit = 0;
for (digit = numb % 10; numb != 0; numb = numb / 10)
{
digit = numb % 10;
sum += digit;
}
if (sum > 9)
reduceToSingle(sum);
else
return sum;
}
In the above code in the if (sum > 9)
block I haven't returned the function value. I just called the function instead. Logically this function should give an incorrect value. But when I ran the above program in my system I got the correct sum of digits in output. I am unable to comprehend the logic behind this behaviour.
It's just undefined behavior and I'm sure you got a warning. It happens to work - tweak the compiler settings or change the compiler altogether and it won't anymore.
In this case I suspect eax
isn't clobbered so you get the expected value, i.e. the last value return
ed by any of the calls. So when you call reduceToSingle
, it will eventually reach return
(when sum <= 9
). From then on the value of eax
will trickle down to the original caller.
This is what i got
815
Original = 815 Single digit = 2009291924
in your code reduceToSingle(numb) is not returning any value in the code so it is something like
printf("%d %d",12);
so a garbage value is printed for the other format specifier
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With