Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C programming recursion segmentation fault

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading