Can someone explain these two types of C++ problems to me. I\'m not understandin
ID: 3917617 • Letter: C
Question
Can someone explain these two types of C++ problems to me. I'm not understanding exactly how the answer is calculated.
Problem 1: What is the output of the following code fragment?
int f1(int base, int limit)
{
if(base > limit)
return -1;
else
if(base == limit)
return 1;
else
return base * fl(base + 2, limit);
}
int main()
{
cout <<f1(2,4)<<endl;
return 0;
}
The output: 2. I see based on f1(2,4) that it chooses return base * f1(base+2,limit); . How does it compute this to get 2?
Problem 2: The recursive definition of a Fibonacci Number is F(n)=F(n-1)+F(n-2), where F(0)=1 and F(1)=1. What is the value of Fib(5)?
Answer: 8. How does it calculate this answer? I see it looking like this: F(5-1) + F(5-2)
Thanks for the help.
Explanation / Answer
Problem 1-
when f1(2,4) is computed
2 is not greater than 4 so this condition is false
2!=4 this is also false
now 2* f1(2+2,4) is called
now f1(4,4) returns 1 as base==limit
so 2*1 is equal to 2 that is why the output is 2.
Problem 2-
Fib(5) = Fib(4) + Fib(3)
Fib(4)=Fib(3)+Fib(2)
Fib(3)=Fib(2)+Fib(1)
Fib(2)=Fib(1) + Fib(0)=1+0=1
therefore
Fib(3)=1+1=2
Fib(4)=Fib(3)+Fib(2)=2+1=3
Fib(5)=Fib(4)+Fib(3)=3+2=5
so Fib(5)=5
if you like the answer please provide a thumbs up.