C programming recursion segmentation fault
Question:
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
Answers:
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
This is because there is no base condition defined in the factorial function to handle the value zero.
int factorial( int x ){
if (x == 0)
return 1;
else
return x* factorial(x-1);
}
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
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
This is because there is no base condition defined in the factorial function to handle the value zero.
int factorial( int x ){
if (x == 0)
return 1;
else
return x* factorial(x-1);
}