I am looking for a way to code a program which will multiply an integer to an exponent using only a recursion loop. I have a very limited understanding of recursion, but have been able to code something to give a factorial:
int fac2(int n)
{
if (n == 1){
return 1;
} else {
return n*fac2(n-1);
}
}
I have a way to find a power already, but it uses a for loop:
int my_power(int x, int e)
{
int i, total;
total = 1;
for (i = 1; i <= e; i++){
total *= x;
}
return total;
}
How can I replace this for loop using recursion?
int my_power (int x, int e) {
if (e == 0) return 1;
return x * my_power(x, e-1);
}
Remember that a recursive function calls itself until some base case is achieved. What is your base case here? Raising a number to a power is liking saying that you are going to multiply some number x amount of times. The hint is to call the recursive function, reducing the power by one until you reach your desired base case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With