Home > Enterprise >  while calculating factorial in c why doesn't operation keep continuing further to negative valu
while calculating factorial in c why doesn't operation keep continuing further to negative valu

Time:03-13

i was writing a recursion program for finding factorials , once x reaches zero why does the operation stop in the called function instead of continuing further to negative values like going -1,-2,-3 and so on as int takes negative values too and keep continuing the operation as it is my own user defined function.

  #include<stdio.h>
int factorial( int x);
int main() {
    int n;
    scanf("%d",&n);

    n=factorial(n);
    printf("%d",n);

    return 0;
}
int factorial(int x){
    int f;
    if(x==0||x==1){
        return 1;
    }
    else{
    f= x*factorial(x-1);
    return f;}
}

CodePudding user response:

When factorial is called with an argument value of 2, it evaluates x==0||x==1 in the if statement. This condition is false, so the “then” clause in the if is not executed, and program control flows to the else.

The else executes f = x*factorial(x-1), in which x is 2 and factorial(x-1) is factorial(1).

Thus we have a recursive call to factorial with an argument value of 1. It evaluates x==0||x==1 in the if statement. This condition is true, so the “then” clause is executed.

The “then” clause is return 1;, so the function returns 1, and program control returns to the caller.

In the caller, we are still evaluating x*factorial(x-1). factorial(x-1) has returned 1, so we have 2*1. So f is set to 2.

The next statement is return f;. So 2 is returned to the caller, and program control returns to the caller, which is main. The program continues executing main.

The program does not continue further to negative values because nothing called factorial with negative values.

  • Related