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
eaxisn’t clobbered so you get the expected value, i.e. the last valuereturned by any of the calls. So when you callreduceToSingle, it will eventually reachreturn(whensum <= 9). From then on the value ofeaxwill trickle down to the original caller.