Can anyone please tell me what does the this Function do? I understand everything till the "(n * GetPower(n, power - 1))" part. I just can't understand it. I do realise what the "n * " does, it multiplies N to the other side, and I also get what "GetPower" does (Recursive function) but I don't understand what "(n, power - 1) does. Anyone care to explain?

Many thanks again,

unsigned long int MyFunction(unsigned short int n, unsigned short int  power) {
    if(power == 1)
     return n;
       return (n * GetPower(n, power - 1));
7 Years
Discussion Span
Last Post by metalclunch

You understand a recursive function but you don't understand its parameters?(n, power - 1)


The power function is one of the first examples of a recursive function.

Basically recursion breaks the problem into smaller and smaller problems, until something can be easily solved.

The first if statement is the "base case" - it's what ensures that the recursive function eventually ends. x^1 = x, so if power == 1, return n. I think that is fairly self explanatory.

The next part is the "recursive case". It breaks the problem into something smaller. since x^n = x*(x^n-1), that is exactly what this does. return (n * GetPower(n, power - 1)); simply gets a smaller and smaller power, until the base case is reached, power = 1.

We can do a simple trace. Asume we're trying to calculate 2^4. call MyFunction(2, 4). It returns 2*MyFunction(2, 3). MyFunction(2,3) returns 2*MyFunction(2,2), which returns MyFunction(2,1). Since power is now 1, MyFunction(2,1) returns 2, and all the other statements can begin to return. Since MyFunction(2,2) returns 2*MyFunction(2,1), which is 2, MyFunction(2,2) return 2*2 = 4...
Make sense? This will be returned, to be multiplied by 2, equals 8. This will be return to be multiplied by 2 again, equals 16. And now that all the recursive calls have returned their results, MyFunction(2,4) can return 16 as the answer to 2^4.

Hope that helps :)


Ahh! Thank you very, very much, Swinefish! That really helped me. +rep!

You understand a recursive function but you don't understand its parameters?(n, power - 1)

Well... Yeah.. I didn't understand what's that comma doing there after 'n'. Now I do. Thinking of it now, it was kinda silly of me. It's very logical if you think it out deeply. :)

Again, thank you very much Swinefish.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.