1k views

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 _________

recategorized | 1k views
0
can someone add pictorial representation of function calling.

As it is calling static int , when calling fun1() next time, it will add with previous value
by Veteran (120k points)
+1
add diagram of function calling it will be good.
0

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 ?

0

@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
yes , i ve got it, my bad, thanx anyway.......do i have to remove the coment or something?, i am new here
#include
int fun1(int n) {
printf("--fun1 call--\n");
static int i = 0;
if(n>0){
++i;
printf("fun1(%d-1)\n",n);
fun1(n-1);
}
printf("fun1(%d)= %d\n",n, i);
return(i);
}
int fun2(int n) {
printf("\n******* fun2 call ********\n");
static int i = 0;
if(n>0){
printf("%d + fun1(%d)\n", i,n);
i=i+fun1(n);
fun2(n-1);
}
printf("fun2(%d)= %d\n",n, i);
return(i);
}
void main()
{
printf("final = %d\n", fun2(5));
}
Check step by step handrun of the code to understand the recursion:
******* fun2 call ********
0 + fun1(5)
--fun1 call--
fun1(5-1)
--fun1 call--
fun1(4-1)
--fun1 call--
fun1(3-1)
--fun1 call--
fun1(2-1)
--fun1 call--
fun1(1-1)
--fun1 call--
fun1(0)= 5
fun1(1)= 5
fun1(2)= 5
fun1(3)= 5
fun1(4)= 5
fun1(5)= 5
******* fun2 call ********
5 + fun1(4)
--fun1 call--
fun1(4-1)
--fun1 call--
fun1(3-1)
--fun1 call--
fun1(2-1)
--fun1 call--
fun1(1-1)
--fun1 call--
fun1(0)= 9
fun1(1)= 9
fun1(2)= 9
fun1(3)= 9
fun1(4)= 9
******* fun2 call ********
14 + fun1(3)
--fun1 call--
fun1(3-1)
--fun1 call--
fun1(2-1)
--fun1 call--
fun1(1-1)
--fun1 call--
fun1(0)= 12
fun1(1)= 12
fun1(2)= 12
fun1(3)= 12
******* fun2 call ********
26 + fun1(2)
--fun1 call--
fun1(2-1)
--fun1 call--
fun1(1-1)
--fun1 call--
fun1(0)= 14
fun1(1)= 14
fun1(2)= 14
******* fun2 call ********
40 + fun1(1)
--fun1 call--
fun1(1-1)
--fun1 call--
fun1(0)= 15
fun1(1)= 15
******* fun2 call ********
fun2(0)= 55
fun2(1)= 55
fun2(2)= 55
fun2(3)= 55
fun2(4)= 55
fun2(5)= 55
final = 55
by Active (2.9k points)

by Active (1.2k points)

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

by (145 points)