Below is the code to reduce a given number to one digit by adding the digits of a number recursively.
For example, if the input signal is 845 , the output signal 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 did not return the function value. I just called the function. Logically, this function should give the wrong value. But when I ran the above program on my system, I got the correct sum of digits on the output. I can not understand the logic of this behavior.
svKris
source share