edited by
2,502 views
1 votes
1 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)?


(A) 3

(B) 7

(C) 9

(D) 18

edited by

4 Answers

Best answer
2 votes
2 votes

Ans D

selected by
0 votes
0 votes

                            f(5)    [n>3 so execute if block ]

                             |         [r=n so r=5]

                   return f(3) + 2     (16+2=18.........returns 18)

                             |

                  return f(2) + r   (11+r=11+5=16...returns 16)

                           |

                 return f(1) + r (6+r=6+5=11...returns 11)   

                          |                                                        

                return f(0) + r   (here f(0) returns 1 and r=5 so total returned =6 ) and go from bottom to up

                          |

                         (here f(0) returns 1) 

           

so finally f(5)=18

edited by
0 votes
0 votes

All procedure calls are mapped w.r.t. stack, so

f(0) : r := 5 : returns 1

f(1) : r := 5 : Return f(0)+r

f(2) : r := 5 : Return f(1)+r

f(3) : r := 5 : Return f(2)+r

f(5) :  r := 5 : Return f(3)+2

Solve from top to bottom and get answer D(18).

Related questions

2 votes
2 votes
3 answers
2
Laahithyaa VS asked Sep 9, 2023
878 views
. What will be the value returned by the following function, when it is called with 11?recur (int num){if ((num / 2)! = 0 ) return (recur (num/2) *10+num%2);else return 1...
0 votes
0 votes
0 answers
4
Mizuki asked Dec 9, 2018
301 views
Are these return types valid for a function in C? Would any of these result in error, or simply will be ignored?1 const void f()2 extern void f()3 static void f()