Recursion Problem

I have a program designed to calculate the power of a number in 3 different ways, defined by 3 different functions. power1 works just fine, but power2 only outputs the base number, y. And power3 outputs the number 1 ad nauseum. Can I please get any help? It would be really appreciated. Thank you!

Here is the program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <cmath>
using namespace std;
int power1(int& x, int& n){

    int i = 0;
    if (n == 0){
        x == 1;
        i++;}
    if (n == 1){
        x == x;
        i++;}
    else {
        unsigned int temp;
        for (temp = x; n > 1; n--){
            temp *= x;
            i++;
        }
        cout << temp << endl;
        cout << "# of multi's: " << i << endl;
    }
}

int power2(int y,int z){
    if (z == 0) cout << "1";
    if (z == 1) cout << y;
    else if (z > 1) {
        cout << y * power2(y, z - 1) << endl;
}
}

int power3(int p, int q){
    if (q == 0) cout << "1\n";
    if (q == 1) cout << p;
    if (q%2 == 0){
        cout << p * (power3((power3(p,(q/2))),2)) << endl;
    }
    else if (q%2 != 0){
        cout << p * (power3((power3(p,((q-1)/2))),2)) << endl;
    }
}
int main(){
    int a, b;
    cin >> a;
    cin >> b;
    power1(a, b);
    power2(a, b);
    power3(a, b);
    return 0;
}
Last edited on
http://www.cplusplus.com/forum/general/112111/ (but the third post would refer to step by step debugging instead)

foo.cpp: In function ‘int power1(int&, int&)’:
foo.cpp:8:5: warning: statement has no effect [-Wunused-value]
foo.cpp:11:9: warning: statement has no effect [-Wunused-value]
foo.cpp:22:1: warning: no return statement in function returning non-void [-Wreturn-type]
foo.cpp: In function ‘int power2(int, int)’:
foo.cpp:30:1: warning: no return statement in function returning non-void [-Wreturn-type]
foo.cpp: In function ‘int power3(int, int)’:
foo.cpp:41:1: warning: no return statement in function returning non-void [-Wreturn-type]


> power1 works just fine
You are a terrible tester
Try b=0 and b=1


As an advice, remove the `cout' statements from inside the `power' functions
1
2
3
cout << power1(a,b) << '\n';
cout << power2(a,b) << '\n';
cout << power3(a,b) << '\n';
I'm new, I know I suck. But thanks for the input.
Topic archived. No new replies allowed.