Below is a function which takes int and return int. Within the function I call the function itself and if i==1, I want to go out of my function.
Basically I'm trying to calculate factorial in recursive manner.
Code Snippet
static int factorial(int i){
result = result * i;
if(i==1){
return 0;
}
factorial(i-1);
return 1;
}
Note - result is an global int variable and is initialize to 1.
Why this function returns 1 instead of 0. [Note when i==1 then with return statement the pointer should come out of the function]
Please don't post better algorithm for factorial, I'm looking for - why this code is behaving a bit different.
example calling factorial(3)
:
int i = factorial(3);
+--------------------------------------------------+
|result = result * 3; |
|if (i==1) { |
| // not executed |
|} |
|factorial(2); |
| +-------------------------------------------+ |
| |result = result * 2; | |
| |if (i==1) { | |
| | // not executed | |
| |} | |
| |factorial(1); | |
| | +---------------------------------+ | |
| | |result = result * 1; | | |
| | |if (i==1) { | | |
| | | return 0; | | |
| | |// nothing more in factorial(1) | | |
| | +---------------------------------+ | |
| |// factorial(1) returned 0 (value not used)| |
| |return 1; // factorial(2) | |
| +-------------------------------------------+ |
|// factorial(2) returned 1 (value not used) |
|return 1; // factorial(3) |
+--------------------------------------------------+
i = 1; // the value returned by last call
factorial(3)
returns 1! recursion was terminated by return 0
, but that value is not being used
Zero would have been returned if the last two lines were joined to return factorial(i-1);
only factorial(1)
will return 0, e.g. int i = factorial(1)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments