edited by
10,260 views
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)$?

  1. $5$
  2. $7$
  3. $9$
  4. $18$
edited by

1 Answer

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.

edited by
Answer:

Related questions

64 votes
64 votes
8 answers
1
Kathleen asked Sep 21, 2014
26,380 views
In the following C function, let $n \geq m$.int gcd(n,m) { if (n%m == 0) return m; n = n%m; return gcd(m,n); }How many recursive calls are made by this function?$\Theta(\...