0
Recursion factorial
Hey guys, kinda new here so i'll get straight to the point. I was looking at the C++ tutorial on Recursion and I asked myself if it would be possible to write it in the form of a for loop and if not why. Now I've barely just learnt how to walk but I'm interested in breaking things to figure out how and why they work. Here's the code I switched from the original website code : #include <iostream> using namespace std; int factorial(int n) { for(int i ; i > 1 ; i--){ return n * factoral(n-i); } } int main() { cout << factorial(5); } any help or explanation is welcome, thanks in advance.
3 Answers
+ 4
Almost all recursive functions are doable as a loop, but may take more code or at times, they can be more efficient. But efficiency for recursion is very rare, because it has to continually backtrack the stack to see what the value was before the function calls itself, ie. it has to store the values each time the function runs, which can easily lead to stack overflow.
The loop equivalent of this is:
#include <iostream>
using namespace std;
int ans = 1;
void factorial(int n) {
for(n; n > 1 ; n--){
ans = ans
* n;
}
}
int main() {
factorial(3);
cout << ans;
}
0
Turns out I've got a lot more to learn than I thought.
Anyways thanks guys, that cleared things up for me.
0
Here is recursive factorial:
https://code.sololearn.com/cM4VQXlTNKYF/?ref=app