What is the output of the following C++ code?
#include <iostream>
using namespace std;
int fun(int n)
{
if (n <= 1)
return n;
return fun(n - 1) + fun(n - 2);
}
int main()
{
cout << fun(5);
return 0;
}
Options
-
A.
3
-
B.
5
-
C.
8
-
D.
More than one of the above
-
E.
None of the above
Correct Answer (Detailed Explanation is Below)
B.
5
Detailed Explanation
Correct Answer: Option BExplanation:This is a recursive Fibonacci function. The base cases are
fun(0) = 0 and
fun(1) = 1. Therefore, fun(2) = 1, fun(3) = 2, fun(4) = 3, and
fun(5) = 5.