in Programming in C retagged by
23,158 views
38 votes
38 votes

Consider the following C functions.

int fun1(int n) {
    static int i= 0;
    if (n > 0) {
       ++i;
      fun1(n-1);
   }
  return (i);
}
int fun2(int n) {
   static int i= 0;
   if (n>0) {
      i = i+ fun1 (n) ;
      fun2(n-1) ;
  }
return (i);
}

The return value of $\text{fun}2 (5)$ is _________

in Programming in C retagged by
by
23.2k views

4 Comments

0
0
1
1
how much time should we give to such type of questions in exam ?

:(
0
0

3 Answers

29 votes
29 votes
Best answer

This illustration of function calling and values may help😀

$$\mathbf{Fig: Tracing\; by\; tree\; method}$$ Now $f1(5),$ if we observe it increments $ ‘i\text{’}, n$ times so $f1(5)$ will return $5.$

Similarly, $f1(4)$ will increment $ ‘i\text{’}$ $4$ times but $ ‘i\text{’}$ being static (just one memory location for entire program run instead of different memory location across function calls), it′ll resume from its previous value of $5.$  So, $f1(4)$ returns $9\;[5+4]$

By the same logic $f1(3)$ will return $12\; [9+3],$

$f1(2)$ will return $14\; [12+2],$

$f1(1)$ will return $15\; [14+1].$

$\therefore$ Return value $i=55$ and hence $55$ is the output of $f2(5).$

edited by

2 Comments

Should we consider i as 2 variables
1
1
yes
0
0
10 votes
10 votes

Answer is 55.it is calling static int , when calling fun1() next time, it will add with previous value.

 

6 votes
6 votes
Answer will be 55

As it is calling static int , when calling fun1() next time, it will add with previous value

4 Comments

add diagram of function calling it will be good.
1
1

my only doubt is "every time we call fun1 , why does it not initialize i to zero in the first statement?and does it allocate space for a new variable " i " every time we call it, keeping the previous variables as it it or there is just one i...kindly explain how many variable i's will be allocated ?

2
2

@RuhanMuzaffar

U mean this statement

static int i= 0;

why will it be initialized more than once? It is a static variable, which keep it's previous value for further calculation. right?

 

0
0
yes , i ve got it, my bad, thanx anyway.......do i have to remove the coment or something?, i am new here
1
1
Answer:

Related questions