Naive recursion no output

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
since you have no cout << ... there will be no output?
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
I tried it with 2 and 3 and it printed 8
can you give us how you used cout?
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
Don't put the std::cout in there. Rather, you should place it where you invoke the function.

cout << power2(a, b);
So what should I put in the function itself in line 5?
You had the function right the first time. It should be returning the value.
Yes!! It worked. Thank you so much guys, I really appreciate it!
Topic archived. No new replies allowed.