0

What is the output of this code & most importantly HOW?

int foo(int n, int r){ if(n>0) return (n % r + foo(n / r, r)); else return 0; } int main(){ printf("%d", foo(345,10)); }

23rd Apr 2020, 7:56 PM
Ashfaq Reshad
Ashfaq Reshad - avatar
3 Respuestas
+ 1
foo(345, 10) 5 + foo(34, 10) 5 + 4 + foo(3, 10) 5 + 4 + 3 + foo(0, 10) 5 + 4 + 3 + 0 = 12 edit: first step is included.
23rd Apr 2020, 8:27 PM
Mustafa K.
Mustafa K. - avatar
+ 19
Ashfaq Reshad It is a code to calculate sum of 345 After function calling first it check the condition if(n>0) in which recursive returns 3 times as - 345/10 = 34 /10= 3/10=3 3%10=3 34%10=4 345%10=5 3+4+5=12
23rd Apr 2020, 8:37 PM
Vinesh Wadhwani
Vinesh Wadhwani - avatar
+ 1
This program shows a recursive function foo, which will call itself until n has become less than Zero... In the function it adds the modulo of n and r to the result of the next call... Now lets Go through it: 1. call: 345 % 10 = 5 2. call: 34 % 10 = 4 3. call: 3 % 10 = 3 4. call: 0 Add together: 12 (which ist the output of the code).. Note, that n is shortend by one digit from right in every next call by integer Division by 10...
23rd Apr 2020, 8:31 PM
G B
G B - avatar