I just started to learn about recursion.
This program is supposed to calculate n! and store the result into an output parameter.
void factorial(int n, int &f)
{
if (n == 0)
{
f = 1;
}
else
{
factorial(n - 1, f);
f *= n;
}
}
int main()
{
int f;
factorial(5, f);
cout << f;
}
This way it works perfectly. In my first attempt, the else condition looked like this
else
{
f *= n;
factorial(n - 1, f);
}
and the program didn't output anything but 1.
I really can't understand why it works in the first way but in the second it doesn't. Can you explain to me?
In your code, factorial(0, f)
will set f = 1
. If you modify f
before the call to factorial
, it will be overwritten.
Note that this problem is not possible if you return int
instead of taking int &
as an argument.
For anyone wondering: Using @ForceBru's suggestion I ran it on a piece of paper and I got it. If I do it in the second way, the last thing called will be factorial(0) which will return 1, even if I already calculated to be n!.
f is getting over written to 1 in your last call f(0). If you switch the statements then f gets initialized to 1 in the last call f(0) followed by It's modification before return of each function call
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.