# Recursion

 Moh Sam · June 22, 2014 I've been watching bucky's c++ tutorials and found all easy until I got to the recursion thing. I do understand what is recursion but I still can't understand how bucky's code for factorial works after watching it for like 2 hours. I would be grateful if someone offers step-by-step explanation with reference to what is happening.PS : I understand the code itself but I can't get how it works to get the factorial at the end.Thanks in advance.https://www.youtube.com/watch?v=4agL-MQq05E&list=PLAE85DE8440AA6B83&index=31 That's the link to bucky's tutorial if anyone wanna check the code.

## Replies

 H. P. Lovecraft · June 23, 2014 Yes, recursion should be avoided if possible. It is more effective to use iteration instead. Moh Sam · June 22, 2014 Thanks Mathias , I got it now. H. P. Lovecraft · June 22, 2014 It takes 5 and multiplies it by the function call factorial(4), the return value of factorial(4) is 4 * factorial(3). factorial(3) gives 3 * factorial(2). factorial(2) gives 2 * factorial(1). Factorial(1) is a base case so it gives the value of 1.factorial(1) = 1factorial(x) = x * factorial(x-1)This is what happens when you call factorial(5)= 5 * factorial(4)= 5 * 4 * factorial(3)= 5 * 4 * 3 * factorial(2)= 5 * 4 * 3 * 2 * factorial(1)= 5 * 4 * 3 * 2 * 1= 120more clear now? ebelos azuz · June 22, 2014 never mind lol ebelos azuz · June 22, 2014 well you should understand all but the last line of code then...no?    basically it's like this, the last line does two things.It multiply 5 by 4 and then it calls the method / function it's in again but instead of x having the value 5 again it now has the value of 4 cos of the x-1 thing.now that x has the value of 4 when it gets to the code again it will be 4 time 3  and so on till x equals 1 then the if(); will return 1 and c++ just use that as an excuse to unload all the numbers from the multiplying.int re(int x);int main(){    cout<
• 1

## C++

120,879 followers