The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+16 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 (52k points)
edited by | 3.3k 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

how many times the function will return 7?

one time or four times? And how it will return.Plz explain.
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.

3 Answers

+28 votes
Best answer
Answer is $7$. As,




$f(7):print(n) \Rightarrow 7$ <ans>
answered by Active (1.9k 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;



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 (101 points)
Initialize k to 1 as you have to calculate f(1). Then you will get answer as 7.

@Sheetal you are not initializing k as 1


Related questions

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
49,576 questions
54,182 answers
71,142 users