• edited by
17,393 views
49 49 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$

3 Answers

Best answer
49 49 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
5 5 votes

Note: Function calls are retained on the stack.

\begin{align*}
    &\text{int } f(5) \\
    &\quad \downarrow \\
    &f(3) + 2 \quad \text{(18)} \\
    &\quad \downarrow \\
    &f(2) + 5 \quad \text{(16)} \\
    &\quad \downarrow \\
    &f(1) + 5 \quad \text{(11)} \\
    &\quad \downarrow \\
    &f(0) + 5 \quad \text{(6)} \\
    &\quad \downarrow \\
   &1 \quad \text{(base case)} \\
    & \\
    &f(5) = 18 = \text{Ans}
\end{align*}

Answer:
Position:
Show:

Related questions

86 86 votes
9 answers 9 answers
39.0k
39.0k views
Kathleen asked Sep 21, 2014
39,031 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(\...
77 77 votes
5 answers 5 answers
20.9k
20.9k views
Ishrat Jahan asked Oct 29, 2014
20,938 views
The function f is defined as follows:int f (int n) { if (n <= 1) return 1; else if (n % 2 == 0) return f(n/2); else return f(3n - 1); }Assuming that arbitrarily large int...
88 88 votes
16 answers 16 answers
57.2k
57.2k views
Arjun asked Jul 6, 2016
57,152 views
Consider the following segment of C-code:int j, n; j = 1; while (j <= n) j = j * 2;The number of comparisons made in the execution of the loop for any $n 0$ is:$\lceil \...
47 47 votes
3 answers 3 answers
15.6k
15.6k views
go_editor asked Apr 23, 2016
15,594 views
Consider the following program segment. Here $\text{R1, R2}$ and $\text{R3}$ are the general purpose registers.$$\begin{array}{|l|l|l|c|} \hline & \text {Instruction} & \...