What will be the output of the following C++ code? long factorial (long a)
What will be the output of the following C++ code?
#include<iostream>
using namespace std;
long factorial (long a)
{
if (a>1)
return (a * factorial (a+1));
else
return(1);
}
int main( )
{
long num = 3;
cout <<num<<"!="<<factorial (num);
return 0;
}
Show answerHide answer
Correct answer: (C) Segmentation fault
Explanation
factorial(a + 1) makes the argument grow (3, 4, 5, ...), so a > 1 is never false. The recursion never ends, the stack overflows, and the program crashes with a segmentation fault.