how to ?

hey guys im studying about recursion by myself and i want to make a recursive function that prompts the user to input the base and exponent and generate the final answer . i have no ideas how to do it can anyone help me?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;
int recursive(int x, int y);
int main()
{

	/*i did the program iterate form first to find ways how to solve it recursively but still its useless i dont know where to start */    
      /*int total=1;
	int y, x;
	cout<<"Enter base : ";
	cin>>x;
	cout<<"Enter exponent : ";
	cin>>y;
	for(int i=0; i<y; i++)
	{
		total*=x;
	}
	cout<<x<<"^"<<y<<" = "<<total;*/ 
}
int recursive(int x, int y)
{
	
}
1
2
3
4
5
6
7
int recursive(int base, int power)
{
    if (power <= 1)
        return base;

    return (base * recursive(base, power - 1));
}
tnks
Note that the solution given by Lazaro Binda only works when power > 0.
Yes, but it's only because that is a function returning int. If you will need power < 0 then you can write:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
float recursive(float base, int power)
{
    if (power < 0 )
    {
        power *= -1;
        base = 1 / base;
    }

    if (power <= 1)
        return base;

    return (base * recursive(base, power - 1));
}
Topic archived. No new replies allowed.