in Programming in C edited by
637 views
9 votes
9 votes

Consider the following recursive function. What is $f(0)?$

int f(int x) {
    if (x > 1000) return x - 4;
    else return f(f(x+5));
}
in Programming in C edited by
637 views

2 Answers

6 votes
6 votes
$f(0)=f(f(5))$

$f(5)=f(f(10))$

$f(10)=f(f(15))$

$f(15)=f(f(20))$

so on…

$f(995)=f(f(1000))$

$f(1000)=f(f(1005))$

now x=1005 >1000 so we return 1001.

so ,

$f(1005)=1001$

$f(1001)=997$

now ,
$f(1000)=f(f(1005))=f(1001)=997$

$f(995)=f(f(1000))=f(997)=f(f(1002))=f(998)=f(f(1003))=f(999)=f(f(1004))=f(1000)=997$

so we can observe that ,$f(995)=f(997)=f(998)=f(999)=f(1000)=997$

say ,we left f(996) behind check for that as well ,

$f(996)=f(f(1001))=f(997)=997$

and so on we can check for all the number till 0 as f(i) where 0<=i <=1001 the value of f(i)=997.

so till x=1001 the value will be 997 . after that the value will be x-4.
edited by
6 votes
6 votes

The answer is 997.

Answer:

Related questions