0

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

1
  • This code would fail in Python, too. A recursion needs a stop condition (just returning a value without further recursion for the most simple input) to work. Commented Nov 12, 2022 at 11:36

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes you are very right, thank you. Is segmentation related the operating system, right ? It is not about the compiler vs
1

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);
       
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.