I'm curious how return works when using a recursive function. For example, in the factorial function below, x will reach 1 before any calculations can actually occur.
int factorial (int x){
if (x==1){
return 1;
}else{
return x * factorial(x - 1);
}
}
Suppose x = 3
. Following the logic, it seems it should loop 3 times and return 1:
3 != 1
- so else:
3 * factorial (2)
. - What's
factorial (2)
? - Well return to top:
2 != 1
- so else:
2 * factorial (1)
. - What's
factorial (1)
? - Return to top:
1 == 1
, - so:
return 1
.
But, of course it will actually return 6. So how does it work, exactly?