What is the output of the following C++ code?

#include <iostream>
using namespace std;
int fun(int n)
{
    if (n == 0)
        return 0;
    return n + fun(n - 1);
}
int main()
{
    cout << fun(4);
    return 0;
}
                        

Options

  • A. 4
  • B. 6
  • C. 10
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

C. 10

Detailed Explanation

Correct Answer: Option C

Explanation:
The calls return 4 + 3 + 2 + 1 + 0. Therefore, fun(4) = 10. This is a recursive sum, not a factorial.