The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+16 votes
2.7k 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$
asked in Programming by Veteran (59.5k points)
edited by | 2.7k 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.

3 Answers

+26 votes
Best answer
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>
answered by Active (2.1k points)
edited by
+14 votes
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.
answered by Active (1.5k points)
+1 vote

so how it is 7

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


Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

38,058 questions
45,554 answers
131,897 comments
48,912 users