+ 8

Why this code prints 32 ?

#include <stdio.h> int recurse(int n){ if(n<=1) return 20; return(3+recurse(n-1)); } int main() { printf ("%d", recurse (5)); return 0; }

31st Jan 2019, 3:35 PM
Mihai C
Mihai C - avatar
4 ответов
+ 8
recursive(5)=> 3+recursive(4)=> 3+3+recursive(3)=> ... 3+3+3+3+recursive(1)=> 3+3+3+3+20= 32
31st Jan 2019, 3:50 PM
Earl_Grey
Earl_Grey - avatar
+ 6
recurse(5) calls recurse(4) recurse(4) calls recurse(3) ... recurse(2) calls recurse(1) recurse(1) returns 20 recurse(2) now returns 20+3=23 recurse(3) now returns 23+3=26 ... recurse(5) Noe returns 29+3=32 main() method outputs 32. That's how it works.
1st Feb 2019, 1:21 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
The resource function will be invoked until de value of "n" is 1 ande it enters the if (n<=1) so that it returns 20 and ends, since it no longer invokes the function resource. 3+4=7 3+2=5 20 n=7+5+20 n=32
2nd Feb 2019, 4:27 AM
DIEGO MAURICIO MORENO SALAMANCA
DIEGO MAURICIO MORENO SALAMANCA - avatar
0
Bro. Thanks for this question. I was stuck asf. Thank you.
2nd Feb 2019, 1:27 PM
.Houdini
.Houdini - avatar