Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My factorial function is not returning factorial

I am not able to find out why my function returns the user input only rather then the factorial of the input.

#include <stdio.h>
#include <math.h>
int factorial(int x)
{
    //int x;
    int sum = 1;
    while (x!=0){
        sum = sum * x;
        x--;
    }
    return sum;
}

int main(){
    int x;
    printf("Enter value of x: ");
    scanf("%i",&x);
    factorial(x);
    printf("sum is %i", x);
    
    return 0;
}
like image 366
mitday Avatar asked Oct 26 '25 05:10

mitday


2 Answers

Your factorial function does return a new value, but then you don't actually use that value.

printf("sum is %i\n", factorial(x));

Note aso that you should be checking the return value from scanf. If scanf in this situation does not return 1, it's indicating a failure to read a value into x. If this is the case, the value of x is indeterminate, and the behavior of the following code is undefined.

An example of what might occur: if the initial value of x is a negative number, factorial only checks that it's input is equal to zero, but does not check if it's less than zero, so the loop might never terminate.

like image 177
Chris Avatar answered Oct 28 '25 19:10

Chris


Because you are printing x which is the variable that you have stored the user input in. Your factorial function returns the result, but you are not saving it.

like image 40
chameleon Avatar answered Oct 28 '25 20:10

chameleon