Naive recursion no output

Feb 10, 2014 at 2:38pm
This function is supposed to take a base number and exponent and calculate the total. The syntax is all fine, but the problem is that no output comes out when I run the program. Here is the program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cmath>
using namespace std;

int power2(unsigned int y,unsigned int z){
    if (z == 0) return 1;
    if (z == 1) return y;
    else {
	return y * power2(y, z - 1);
    }
}

int main(){
    int a, b;
    cin >> a;
    cin >> b;
    power2(a, b);
    return 0;
}


Any suggestion would be great. Thank you!
Last edited on Feb 11, 2014 at 1:39am
Feb 10, 2014 at 2:56pm
since you have no cout << ... there will be no output?
Feb 10, 2014 at 3:24pm
I tried putting in cout << ... and then it printed the value of y along with some really strange numbers. For example, if I put 2 as the base number and 3 as the exponent this is the output:
1
2
212591936
12591936
Feb 10, 2014 at 4:04pm
I tried it with 2 and 3 and it printed 8
can you give us how you used cout?
Feb 10, 2014 at 4:05pm
1
2
3
4
5
6
7
int power2(int y,int z){
    if (z == 0) return 1;
    if (z == 1) return y;
    else if (z > 1) {
	cout << y * power2(y, z - 1) << endl;
}
}
Last edited on Feb 10, 2014 at 4:10pm
Feb 10, 2014 at 4:21pm
Don't put the std::cout in there. Rather, you should place it where you invoke the function.

cout << power2(a, b);
Feb 10, 2014 at 4:29pm
So what should I put in the function itself in line 5?
Feb 10, 2014 at 4:49pm
You had the function right the first time. It should be returning the value.
Feb 11, 2014 at 1:31am
Yes!! It worked. Thank you so much guys, I really appreciate it!
Topic archived. No new replies allowed.