26 votes 26 votes Consider the following C function: int f(int n) { static int r = 0; if (n <= 0) return 1; if (n > 3) { r = n; return f(n-2) + 2; } return f(n-1) + r; } What is the value of $f(5)$? $5$ $7$ $9$ $18$ Programming in C gatecse-2007 programming recursion normal + – Kathleen asked Sep 21, 2014 edited Oct 17, 2018 by Mk Utkarsh Kathleen 10.3k views answer comment Share Follow See all 8 Comments See all 8 8 Comments reply Show 5 previous comments blackflamemaster commented Dec 25, 2022 reply Follow Share Yes, can you please explain this? How it becomes unreachable? 1 votes 1 votes mahendrapatel commented Jan 15, 2023 reply Follow Share How static variable is assigned by local variable n??? It should error 0 votes 0 votes parag parab commented Jan 2 reply Follow Share https://www.youtube.com/watch?v=JjQdpl4kmxE 0 votes 0 votes Please log in or register to add a comment.
Best answer 36 votes 36 votes The answer is D. $f(5) = 18.$ $f(3) + 2 = 16 + 2 = 18$ $f(2) + 5 = 11 + 5 = 16$ $f(1) + 5 = 6 + 5 = 11$ $f(0) + 5 = 1+5 = 6$ Consider from last to first. Since it is recursive function. Gate Keeda answered Jan 22, 2015 edited Jan 26, 2018 by kenzou Gate Keeda comment Share Follow See all 12 Comments See all 12 12 Comments reply Show 9 previous comments haider000 commented May 24, 2020 reply Follow Share no you can not execute two return statement in a single function as soon as the first return statement runs then all the other statement after that return statement will not execute no matter what statements they are. 1 votes 1 votes Shubham Pande commented Nov 1, 2020 reply Follow Share what would be the answer if declaration of variable and its initialisation were on saperate lines?…...my doubt is regarding the fact that static only means that variable only has one copy so used by all calls so r=0 will make r 0 .In current case ...is r=0 ignored because it is combined with declaration and declaration is only done once. can somone clarify all this?? 0 votes 0 votes Jain07 commented Sep 17, 2023 reply Follow Share how you have directly written f(5) 18 not understandable please explain clearly 0 votes 0 votes Please log in or register to add a comment.