The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+14 votes

Consider the following C function:

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

The value returned by $f(1)$ is

  1. $5$
  2. $6$
  3. $7$
  4. $8$
asked in Programming by Veteran (69k points)
edited by | 2k views
re: n=n+I,

but how come I came here???
Sorry, it was a typo. Corrected now.
when i saw the paper there was a typo error there also brother return is written in a wrong way . :)
That was silly- corrected now :)
@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) ??

might this will help to better understand

3 Answers

+22 votes
Best answer
answer is $7$.as,




$f(7):print(n) \Rightarrow 7$ <ans>
answered by Active (2.3k points)
edited by
+13 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;



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



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



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 (127 points)
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

33,593 questions
40,128 answers
38,389 users