Recursion

0 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.

Post a Reply

Replies

Oldest  Newest  Rating
0 Moh Sam · June 22, 2014
I don't think I'd like to learn a new programming language unless I'm already done with the previous one (C++ atm).
0 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<<re(5)<<endl;
}

int re(int x){
    if(x==1){
        return 1;
    }else{
        return x*re(x-1);
    }
}


</re(5)<<endl;
0 ebelos azuz · June 22, 2014
never mind lol
0 Moh Sam · June 22, 2014
Thanks Mathias , I got it now.
  • 1

C++

131,241 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator