Hello, what the title says, I'm really confused with recursion. I understand the basics like what we actually call a recursive method (a method that calls itself within its body) but I can't seem to understand how it is used (especially the factorial example). OK, the following example is the classic recursive way to find the factorial of a number. I will write the code (pseudo-code) and then tell you what I can't seem to understand. BTW, sorry if my English ain't that good, I'm neither English nor American.
int fact(int n)
{
if (n == 1) return 1;
else return fact(n - 1) * n;
}
First things first, I know the factorial of a number is given by the following math expression: n! = 1 * 2 * 3 * ... * (n - 1) * n (as an example) which leads us to this expression: n! = (n - 1)! * n (which is used in the code above). So what I don't understand is if we actually have the method call itself with parameter n - 1 before the operation (*) is evaluated, how we get the factorial of the number. The way I see things, constantly calling fact(n - 1) when the method tries to return will result in an infinite amount of times the method being called without returning anything. Also, I thought that when the return statement was used, something must actually be returned to the point in the code where the method is called (eg. int fact = fact(5); will result in variable "fact" being assigned to 120). I would so much appreciate it if you could break it down for me step by step, what exactly happens when the method calls itself again that is. Do you think you can help me?
P.S: The question may sound kinda dumb to you but I'm a 15 year old self taught programmer who hasn't been taught functions let alone factorials at school as of yet so it is harder for me to understand. Again, keep it simple if you can.
Thank you in advance.