0
// Ex5_15.cpp (based on Ex5_01.cpp)
// A recursive version of x to the power n
#include <iostream>
using std::cout;
using std::endl;
double power(double x, int n); // Function prototype
int main(void)
{
    double x(2.0); // Different x from that in function power
    double result(0.0);
    // Calculate x raised to powers -3 to +3 inclusive
    for(int index = -3; index <= 3; index++)
    cout << x << “ to the power “ << index << “ is “ << power(x, index)  <<  endl;
    return 0;
}
// Recursive function to compute integral powers of a double value
// First argument is value, second argument is power index
double power(double x, int n)
{
    if(n < 0)
    {
        x = 1.0/x;
        n = -n;
    }
    if(n > 0)
        return x*power(x, n-1);
    else
        return 1.0;
    }

I am in school taking classes for programming. This is an example for recursive functions given in the book. I don't quite see what they are doing and the techniques involved. I was just wondering if anyone can explain this to me or at least point me in the right direction so I can better understand this technique.

Eric Wood
  • 63
  • 6
  • 3
    Why not use a pencil and a sheet of paper and write out the steps of power with the values of `x` and `n` for a new values of `x` and `n` to get an idea of what is going on – Ed Heal Jan 06 '16 at 22:02
  • 1
    Ask your lecturer/teacher, they'll be able to explain to you. – AStopher Jan 06 '16 at 22:06
  • The teacher does not seem to directly address the issue at hand and the book falls short of explaining it I feel. I have found much better answers and understanding from this website. – Eric Wood Jan 06 '16 at 22:14
  • 1
    As another strategy for gaining more understanding: use your debugger to step through the code line by line (stepping into the function calls). If you don't know how to do that: now is a good time to learn how to use your debugger. Hint: if your debugger supports it (e.g. Visual Studio) also have it show the call stack and note how it changes. – CompuChip Jan 06 '16 at 22:18
  • @jxh - "Explain this code to me" questions are off-topic on Programmers. –  Jan 06 '16 at 22:18
  • @jxh: No, it doesn't. – Lightness Races in Orbit Jan 06 '16 at 22:20
  • @LightnessRacesinOrbit: Okay, can it be rewritten as a "please explain how recursion works" question? – jxh Jan 06 '16 at 22:22
  • @jxh: Doesn't matter as that would still be off-topic. – Lightness Races in Orbit Jan 06 '16 at 22:23
  • Possible duplicate of [How Recursion works in C](http://stackoverflow.com/questions/5631447/how-recursion-works-in-c) – Ziezi Jan 06 '16 at 22:24
  • @LightnessRacesinOrbit: The site FAQ does not do a very good job at explaining what is off-topic, then. – jxh Jan 06 '16 at 22:26
  • @jxh: Indeed. In fact I was hoping you'd ask "then what _is_ on-topic on Programmers.SE?" so I could give my answer: _nobody knows_. – Lightness Races in Orbit Jan 06 '16 at 22:29
  • Well as long as people are searching for knowledge then it's all good – Eric Wood Jan 06 '16 at 22:37
  • @EricWood, SO is not meant to teach you principles of software programming, I suggest you try to learn such things from video lectures and/or books. Recursion is simple topic and there are many resources available on net for it – Raj Kamal Jan 07 '16 at 04:07
  • As I have stated previously, I am using textbooks, lecture videos and everything you have just named but am just trying to understand it better. Where does it say that Stack Overload is not the place to be learning these things? At one point everyone was where I am right now. I am just trying to learn. – Eric Wood Jan 07 '16 at 05:59

2 Answers2

2

Let's have a look what happens when you call power(2,3) :

double power(double x, int n) { // x = 2, n=3; 
   if (n<0) {...}  // false, so skip the brackets  
   if (n>0)        // true
      return x*power (x; n-1);  // call power() again, with different paraleters
   ...             // the rest is skipped
}

So it returns 2 * power(something). Before being able to compute the return value, power() has to call itself again. It's a recursive call. You can see this as if another copy of the function that would be executed, with its own variables (i.e. without touching the local variables of calling instance).

  • So now power() is called with the parameters x=2 and n=2. The flow of execution is similar and it will return 2 * power(x, n-1) but n-1 being now 1. So here a recursion again.

    • Now power() is called with x=2 and n=1. This will return 2 * power(x, n-1), but n-1 being now 0. And a recursion again;

      • Finally, power will be called with x=2 and n=0. Here the flow of execution will skip the two ifs and will end up execcuting the elese branch because n is 0. It will return 1.

        Now we have all the elements, for computing the value by winding up these successive calls

All this can be shown graphically:

power(2,3) 
   |
   +--> 2 * power(2,2)
              |
              +--> 2* power(2,1) 
                        |
                        +--> 2* power(2,0) 
                                  |
                                  1

So in the end it returns 2*2*2*1 which is 2^3, the intended result.

By generalizing further this reasoning, you may use mathematical induction to prove that for any n>=0, power (x, n) will return x^n. I let you finish the exercise by looking yourself at what happens when n is negative.

And here some furhter reading that could help with some graphical explanations under different perspecives.

Christophe
  • 68,716
  • 7
  • 72
  • 138
1

There are always two parts to a recursive function: the recursion and the bottom. Recursion simply means computing the result in terms of a somewhat smaller version of the same problem. The bottom is the final case, where the recursion stops. In the example code, the bottom occurs when n is 0, and the result for that case is 1.0. The recursion occurs when n is greater than 0; it multiplies x by the smaller case of power(x, n-1). Since each recursion reduces n by 1, eventually you hit the bottom, get the result there of 1.0, and return up the chain of calls doing the multiplications until you hit the top-level call, which gives the result. As Ed Heal suggested in his comment, try it with pencil and paper.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165