+ 1
someone please explain recursion to me using the example below.
#include <iostream> using namespace std; int factorial(int n) { if (n==1) { return 1; } else { return n * factorial(n-1); } } int main() { cout << factorial(5); } I don't understand why or how the int factorial function continues to loop until n=1 even though there is no for or while statement.
5 Answers
+ 7
The function itself is recursive, meaning that the function calls itself when needed.
int factorial(int n) {
if (n==1) {
return 1;
}
else {
return n * factorial(n-1);
}
}
// function factorial returns n and proceeds to calls itself whenever n is not 1. If n is 6, the layout will be:
6 * (6-1) * ((6-1)-1) * ... all the way until 1.
+ 7
The function doesn't handle factorial 0 btw lol.
+ 7
What the others said!
Here's another way to visualize factorial's returns on that cout line in case it makes it more clear:
cout << factorial(5);
cout << 5 * factorial(5-1);
cout << 5 * 4 * factorial(4-1);
cout << 5 * 4 * 3 * factorial(3-1);
cout << 5 * 4 * 3 * 2 * factorial(2-1);
cout << 5 * 4 * 3 * 2 * 1;
cout << 120;
Once n hits 1, it meets the condition of the if-statement and stops calling itself in the return.
But yeah, passing a 0 or negative argument to this function would make it sad.
+ 6
The function keeps calling itself giving an argument equals to "n" parameter - 1, and it's bound to reach 1 if the original argument given is greater than 0 (to be honest, this function isn't quite safe, negative numbers would never reach 1, making the program break).
Once it reaches 1, all of the methods called start returning the value, until the control returns to the original function, which terminates, returning the result.
Now, I don't suggest using recursive functions, they're very unsafe, and they're generally considered a bad practice.
+ 4
5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
When factorial() function is with a argument 5 the following happens
factorial(5) calls factorial(4)
factorial(4) calls factorial(3)
.
.
factorial(2) calls factorial(1)
which is equal to 1 and retuns one to the factorial(2). factorial(2) multiplie the retun value with 2 and sends it to factorial(3) .......so on
everytime factorial(n) funtion is called, first the if condition is checked to see if n=1 or not, if its equals to 1 the function returns 1 else it executes the else statement and calls factorial(n-1). and the same process reapeats for the new function call with the new argument. So for or while loops are not required if we are using recursion
factorial(5)
5 * factorial(4)
4 * factorial(3)
3 * factorial(2)
// if condition not satisfied
so calls factorial(1)
2 * factorial(1)
//returns 1 because
if condition is
satisfied