• edited by
21,464 views
49 49 votes

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$

4 Answers

Best answer
47 47 votes
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 by
19 19 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.
1 1 vote

C​​​​​​

f(1) is called .

static int i= 1 gets executed only after first func call after the subsequent func calls this line gets is not executed . 

if( n>=5) : this condition is false for n= 1 

n = n + i // n becomes 2 

i++; after this line i becomes 2 

return f(2) // f(2) is called 

again this condition ( n>= 5 ) becomes false 

Now n becomes 2+ 2 = 4

i becomes 3

f(4) is  called 

again this condition ( n>=5) becomes false 

Now n becomes 4+3= 7 

i becomes 4 

f(7) is called 

Now this condition (n>=5) becomes true 

return n // 7 gets returned 

Answer:
Position:
Show:

Related questions

60 60 votes
4 answers 4 answers
22.4k
22.4k views
Kathleen asked Sep 18, 2014
22,439 views
Consider the following C program segment:char p[20]; int i; char* s = "string"; int length = strlen(s); for(i = 0; i < length; i++) p[i] = s[length-i]; printf("%s", p);Th...
39 39 votes
3 answers 3 answers
13.8k
13.8k views
Kathleen asked Sep 18, 2014
13,799 views
The goal of structured programming is to:have well indented programsbe able to infer the flow of control from the compiled codebe able to infer the flow of control from t...
60 60 votes
9 answers 9 answers
32.6k
32.6k views
Kathleen asked Sep 18, 2014
32,630 views
In an $SR$ latch made by cross-coupling two NAND gates, if both $S$ and $R$ inputs are set to $0$, then it will result in$Q = 0, Q' = 1$$Q = 1, Q' = 0$$Q = 1, Q' = 1$Inde...
30 30 votes
1 answers 1 answer
8.9k
8.9k views
Kathleen asked Oct 9, 2014
8,883 views
A critical section is a program segmentwhich should run in a certain amount of timewhich avoids deadlockswhere shared resources are accessedwhich must be enclosed by a pa...