I'm just new to this Recursion and I know at least that it is a technique by which a method calls itself during execution but I am quite confused on how it actually works.
From the book at school, implementing the factorial function is the first example that was given.
//int n = 5; private static int factorial(int n) { if(n == 0) { return 1; } else return n * factorial(n - 1); } I get how this factorial works somehow but I am not completely sure if I understood it correctly. For every call the method refers to itself, n is multiplied to the factorial parameter n - 1 until it reaches 1.
This is how I trace this recursion in my mind
5 * factorial(5 - 1) = 20 //first call 20 * factorial(4 - 1) = 60 //second call 60 * factorial(3 - 1) = 120 //third call 120 * factorial(2 - 1) = still 120 // fourth call 120 is the last returned value; And another example that was given is printing numbers from 1 to n using recursion instead of using the ordinary loop.
//int n = 10; private static void printNumbers(int n) { if(n >= 1) { printNumbers(n - 1); System.out.print(n + " "); } } This outputs: 1 2 3 4 5 6 7 8 9 10
And now, the thing confuses me here is why the ouput starts at 1? Because from how I understand it the output should start at 9 up to 1.
Because from I understood it, at start the n = 10 and then 10 > 1 so of course it will call itself again then 10 - 1 then print 9 and then calls itself again and 9 - 1 then print 8 and so on...
Can anyone please clarify this to me simply and correct my mistaken understanding to the examples I've mentioned, I am a little confused here and most of the post I can see here on StackOverflow about recursion is not really helping (But if there is a real good and clear answer about recursion in here that you know of, do give me the link).
Thank you...
factorial(5) = 5 * factorial(5-1);factorial(5) = 5 * (4 * factorial(4-1));factorial(5) = 5 * (4 * (3 * factorial(3-1))and so onprintNumbers(9-1)before printing the9; but, again,printNumbers(8)callsprintNumbers(8-1)before printing the7; and so on till theiffails