I'm learning C and came up with this one-line factorial function using a ternary operator on the return, but it always returns 1.
#include <stdio.h>
int factorial(int n){
return (n > 1) ? factorial(n -1) : 1;
}
int main() {
for(int i = 0; i < 10; i++){
printf("%d factorial is %d\n",i,factorial(i));
}
return 0;
}
You can see the code returns 1 for values 0 through 9 in this link: https://code.sololearn.com/c7uSnfxw92sl/#c
That is very easy since we can use the substitution rules. Eg.
Your function is broken. It does not multiply n with the result of factorial(n - 1). You could also do it with an accumulator for it to become tail recursion, but you cannot just replace it with
factorial(n - 1)since it will not compute the same asfactorial(n).