0
How the output of this code is come as 17. When I calculated it gives me 18?
#include <stdio.h> int f(int n) { static int r = 0; if (n <= 0) return 1; if (n > 3) { r = n; return f(n-1)+r; } return f(n-2)+r; } int main() { printf("%d", f(5)); } Please explain the steps of code.
2 Réponses
0
I think 18 seems like the right answer.
Function calls(working):
1.f(n-1)+r;//n=5
2.f(n-1)+r;//n=4
3.f(n-2)+r;//n=3
4.f(n-2)+r;//n=1
5.1;//n=-1.
Edit:
Now, after function call returns the final value 1, we add the returned values to the value of the static variable r(which now has value 4 for any function call).
((((1+4)+4)+4)+4)
=(((5+4)+4)+4)
=((9+4)+4)
=(13+4)
=17.
Point is evaluation is done after last function returns a value so static variable r's value remains unchanged i.e. 4.
0
Arnold D'Souza but on executing the code will return 17 so I think there is something which I'm doing wrong