Recursion factorial | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.

21st Nov 2017, 11:47 PM
Kopano Phutiyagae
Kopano Phutiyagae - avatar
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; }
22nd Nov 2017, 12:12 AM
Hassie
Hassie - avatar
0
Turns out I've got a lot more to learn than I thought. Anyways thanks guys, that cleared things up for me.
23rd Nov 2017, 11:58 AM
Kopano Phutiyagae
Kopano Phutiyagae - avatar
7th Dec 2017, 6:18 AM
#RahulVerma
#RahulVerma - avatar