### Return value malfunctioning in function

when I run the following code below, I get the right answer which is 5040.

 ``123456789101112131415161718192021222324`` ``````#include using namespace std; int factorial(int x){ if (x==0) { return(1); } else { int p; x*= factorial(x-1); return(x); } } int main() { cout << factorial(7); }``````

But if i change the return Value in the if statement to return(2), i get 10080.
or (return value in if statement multiplied by original answer which is supposed to be produced.

 ``123456789101112131415161718192021222324`` ``````#include using namespace std; int factorial(int x){ if (x==0) { return(2); } else { int p; x*= factorial(x-1); return(x); } } int main() { cout << factorial(7); }``````

why is the return value of the if statement affecting the return value of the else) statement?

thanks.
Last edited on
It's because of the recursive nature of the function.

The last thing that is done is multiply by 2, so it then returns 10080.

You shouldn't need to go all the way to zero, stop at` x == 1`

There are probably some other improvements as well.
Thanks I now get it.

but what if i want the if statement to return 2,3 or any other value when equal to zero, and avoid multiplying the 'if' return value with the else return value;

because the result will be affected by the return values of the if statement