I am trying to using with recursion function. But I got failed which is segmentation fault.
#include <stdio.h>
int factorial( int x );
int main(){
factorial(4);
return 0;
}
int factorial( int x ){
return x* factorial(x-1);
}
I have seen the same code in Python and C programming does not give the same success. I’m wondering why and how can I get around this problem
>Solution :
The problem is that you didn´t tell the factorial function when should it end.
Try instead
long factorial(int x) {
if (n == 0)
return 1;
else
return(x * factorial(x-1));
}
Like this when it reaches the number 0 is gonna Stop and return the factorial from x.
This works because the factorial of a number n is given by:
n * n-1 * n-2 * … * 1. But you are traying to calculate it like n * n-1 * … * -inf