Ad

Segmantation Fault In Recursive Function

- 1 answer

i am trying to find factorial by recursively.My function works but why i recieve "segmenatation fault (core dumped)" when i input -1.

#include <stdio.h>

int fak(int number);

int main(){

    int i;
    printf("give me an integer: ");
    scanf("%d",&i);

    printf("factorial: %d\n",fak(i));

    return 0;
}

int fak(int number){

    if(number == 1 || number == 0){
        return 1;
    }

    return number * fak(number - 1);
}
Ad

Answer

To answer the question: you will get a stack overflow because your recursive method will never end normally (see all the comments).

If you put in -1, the method will be called again with -2. It depends on your stack-size when it will crash.

You can change your condition to:

if(number <= 1){
    return 1;
}

Besides of that: the factorial of -1 doesn't exist.

Ad
source: stackoverflow.com
Ad