Hey - I'm new asking questions here. I'm writing a simple program to give a number to a power using a recursive function (inconvenient, but that's the assignment). It seems as though the program should work, and debugging shows that it almost does. It has the right value up until it's about to return, and then it jumps back and multiplies the value further. For the purposes of debugging, it has been modified to only take 5^3.
Take a look:

// Recursive Power Program

#include <iostream>

using namespace std;

int power(int, int, int);

int main()
    int num = 5, pow = 3, full;
    //cin >> num; - out for the purposes of debugging; the program will return 5^3
    //cin >> pow;
    full = num;
    cout << power(num, pow, full);
    char response;
    cin >> response;

int power(int num, int pow, int full)
    if (pow > 1)
    full = num * full; //Multiplies the original number by itself, and sets the new amount to full
    return (num * power(num, --pow, full)); //Multiplies the original number by full again and again until pow is 1
    cout << full; //Just to make sure full had the correct value here (it did)
    return full; //The problem is here. Full = 125 here, but it then jumps back up to the return in the IF statement above, multiplying it 3 more times...

I'm totally confused as to why this would happen. Any ideas?

The if statement is wrong. It should be:

if (pow > 1)
    full = num * full; 
    return (power(num, --pow, full)); //You've already multiplied once. Don't do it again.

Also, your code breaks when pow = 0. Anyway, it's an easy thing to fix.

Good Catch
This article has been dead for over six months. Start a new discussion instead.