Function's function

This is kind of a silly question but I came across this question and can't seem to understand how it works.

1
2
3
4
5
6
7
8
9
10
11
 int Function (unsigned int val) {
		
		if (val > 1) {
			return Function(val - 1)*val;
			

		}
		else;
		return 1;
	}


This is supposed to calculate the factorial of a value val when >1. If I pass in 5 for example, it will go into the if statement and return (5-1)*5 which is not equal to 120. Can someone explain how this works?
Last edited on
> If I pass in 5 for example, it will go into the if statement and return (5-1)*5
No, read again. It would return Function(5-1) * 5, or Function(4) * 5 if you prefer.
Then you may realise that
5! = 1 * 2 * 3 * 4 * 5
1 * 2 * 3 * 4 = 4!
5! = 4! * 5
If I pass in 5 for example, it will go into the if statement and return (5-1)*5 which is not equal to 120.

If the code looked like this, your interpretation would be correct:
1
2
3
    if (val > 1) {
        return (val - 1)*val;
    }

But it actually says this:
1
2
3
    if (val > 1) {
        return Function(val - 1)*val;
    }


In other words, if you pass in 5, it will return Function(4)*5;
So now we have to ask, what is Function(4)?

Well, similar logic applies, Function(4) will return Function(3) * 4

... and so on until we get to Function(1) which (despite the misplaced semicolon in the original code) should take the else path and return just 1.

In other words, your example of Function(5) actually has the function call itself repeatedly, doing one multiplication on each call.
There is a name for algorithms of this nature: recursion / recursive.

Look up that name.
recursion works like calling any other function from inside a function.
the current function suspends and invokes the called function. That does what it does (maybe calling more functions) until it returns a result, and the caller resumes from that point.

It makes no difference to the machine that the function called is the same one it is currently inside.

Topic archived. No new replies allowed.