Return value malfunctioning in function

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
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

how do i go about this? thanks


Last edited on
Topic archived. No new replies allowed.