What will be the output of the following C++ code?
2023
What will be the output of the following C++ code?
- A.
6
- B.
24
- C.
Segmentation fault
- D.
More than one of the above
- E.
None of the above
Attempted by 150 students.
Show answer & explanation
Correct answer: C
The given C++ code has a logical error in the recursive function `factorial`. The function is defined as `factorial(a+1)` instead of `factorial(a-1)`. This means the value of `a` increases with each recursive call, so the base case `a <= 1` is never reached. As a result, the recursion continues indefinitely, leading to a stack overflow. In most systems, this causes a segmentation fault. Therefore, the program will not produce a numerical output but will crash with a segmentation fault.