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