What is the output of the following C++ program?
#include <iostream>
using namespace std;
int fun(int n)
{
if (n <= 1)
return 1;
n = n - 1;
return n + fun(n);
}
int main()
{
cout << fun(4);
return 0;
}
Options
-
A.
4
-
B.
6
-
C.
7
-
D.
More than one of the above
-
E.
None of the above
Correct Answer (Detailed Explanation is Below)
C.
7
Detailed Explanation
Correct Answer: Option CExplanation:For
fun(4), n becomes 3 and returns
3 + fun(3). Then fun(3) returns
2 + fun(2), and fun(2) returns
1 + fun(1). The base case returns 1, so the total is
3 + 2 + 1 + 1 = 7. Each call has its own local copy of n.