2.9k views

Consider the following C function:

int f(int n)
{
static int i = 1;
if(n >= 5) return n;
n = n+i;
i++;
return f(n);
}

The value returned by $f(1)$ is:

1. $5$
2. $6$
3. $7$
4. $8$
edited | 2.9k views
0
re: n=n+I,

but how come I came here???
0
Sorry, it was a typo. Corrected now.
0
when i saw the paper there was a typo error there also.now also brother return is written in a wrong way . :)
0
That was silly- corrected now :)
0
@Arjun sir just basic doubt plz clear
here when if condition becomes true than return statement will executed so it means it will return the value of n and come out of the function call ryt ?
but here wt does the meaning of last return statement ie return f(n) ??
+7

might this will help to better understand

0
how many times the function will return 7?

one time or four times? And how it will return.Plz explain.
0
only single time 7 will be returned. bcoz f(7) will return 7 to f(4), f(4) now will return 7 to f(2), and f(2) will return 7 to f(1) and f(1) will return 7 to main function.

Answer is $7$. As,

$f(1):n=2,i=2$

$f(2):n=4,i=3$

$f(4):n=7,i=4$

$f(7):print(n) \Rightarrow 7$ <ans>
edited
Static storage class allows to initialize a variable for one time and re-initialization can't be done till end of program .

Here Iteration1: n(1)<=5; and  i=1;

n(2)=n(1)+i(1);

i(2)=i(1)+1;

Iteration2: n(2)<=5; and  i=2;

n(4)=n(2)+i(2);

i(3)=i(2)+1;

Iteration3: n(4)<=5; and  i=3;

n(7)=n(4)+i(3);

i(4)=i(3)+1;

Iteration2: n(7)<=5; and program execution terminates . So 7 is returned.
+1 vote

so how it is 7

0
Initialize k to 1 as you have to calculate f(1). Then you will get answer as 7.

1
2