GATE | GATE-CS-2007 | Question 85

Consider the following C function, what is the output?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
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;
}
  
int main()
{
    printf("%d", f(5));
}

chevron_right


(A) 5
(B) 7
(C) 9
(D) 18


Answer: (D)

Explanation:

f(5) = f(3)+2  
The line "r = n" changes value of r to 5.  Since r 
is static, its value is shared be all subsequence 
calls.  Also, all subsequent calls don't change r
because the statement "r = n" is in a if condition 
with n > 3.

f(3) = f(2)+5
f(2) = f(1)+5
f(1) = f(0)+5
f(0) = 1

So f(5) = 1+5+5+5+2 = 18 


Quiz of this Question

My Personal Notes arrow_drop_up
Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.