+ 1

Can u teach how to do recursion

23rd Jul 2017, 3:55 AM
Shruti Pandey
Shruti Pandey - avatar
4 Respostas
+ 3
There's a section on it in the course. Basics: Recursion is a method that calls itself. To make a recursion method, all recursive methods should have the following: * An "easy case" This is essentially a condition that will STOP the recursive calls. * And of course, the call itself. This is the prime example of simple recursion/ Factorials. int factorial(int num){ if(num <= 1) return 1; // This is the "easy case" return num * factorial(num-1); } Lets say I call the method: int fact = factorial(4); Initially this will run: return 4 * factorial(4-1); Ok, what's factorial(4-1) equal to? return 3 * factorial(3-1); Ok, what's factorial(3-1) equal to? return 2 * factorial(2-1); Ok, what's factoral(2-1) equal to? return 1; Therefore, (In reverse) factorial(3-1) equals 2 * 1 = 2. factorial(4-1) equals 3 * 2 = 6. Therefore, factorial(4) equals 4 * 6 = 24. Therefore 4! = 24.
23rd Jul 2017, 4:50 AM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Tnk u evry1
3rd Jul 2020, 3:00 PM
Shruti Pandey
Shruti Pandey - avatar
0
I have a few examples of recursion u nder my code if you would like to use them as references.(shameless self promotion). If you really want to learn more about recursion though, you should learn about the call stack, which is how the functions you call are sorted. (incomplete functions go to the call stack when a new one is called, so that the most recently called function is at the top. Once the top function is completed your code will work it's way down the call stack, completing functions until it makes it's way to the first one you called.)
23rd Jul 2017, 6:21 AM
Gabe Vogel
Gabe Vogel - avatar
0
if you have any additional questions I would be happy to answer, I understand that my explanation is rather confusing
23rd Jul 2017, 6:22 AM
Gabe Vogel
Gabe Vogel - avatar