I have the following task:
Write a program that asks for a number and a power. Write a recursive
function that takes the number to the power. For example, if the
number is 2 and the power is 4, the function will return 16.
I wrote a program and there are no errors when I compile it, but when I start the program and enter a value gives an error saying “Stack Overflow”. I suppose my recursive function became infinite but I have no idea how to write it in other way.
This is my code:
#include <iostream>
using namespace std;
int powpow(int number);
int main(){
cout<<"Enter number:";
int x;
cin>>x;
cout<<"The result of ("<<x<<" * "<<x<<") * "<<x*x<<" is: "<<powpow(x);
system("pause");
return 0;
}
int powpow(int number){
int result = number*number;
return powpow(result);
}
You have no terminating condition for your recursion, so it runs forever.
It sounds like maybe you don’t have a good grasp of recursion, so I’d like to start with something a little simpler, the Fibonacci sequence.
Any time we define a function in terms of recursion, we need to first define a base case(s). In the case of Fibonacci, we have 2 base cases:
That says, in english, “F of 0 is 0, F of 1 is 1”. Or even more simply, if we pass 0 to function F, we will get 0 back. If we pass 1, we will get 1 back.
Once we have the base cases defined, then we need to look for a recurrence relation. In the case of Fibonacci, we have the following recurrence:
F(n) = F(n-1) + F(n-2)
So for
n >= 2, we can use the above recurrence. Why? Well, lets try it for n = 2.So now we know that the answer to F(2) is 1. And what’s more, we can now compute the answer to F(3). Why? Well, what do we need to compute F(3)? We need F(2) and F(1). We now have both of those answers since F(1) is a base case, and we just solved F(2) above.
So, now let’s try to write a piece of pseudo code to solve F.
Note that in a recursive function, we always handle the base cases at the beginning of the function. We cannot define this recurrence if we don’t have base cases in place, otherwise, we will have no terminating condition for our recurrence. So that’s why you always put the base cases at the beginning of the function.
Now, given the above explanation, another good exercise would be to write a recursive function for the factorial function. So, follow these steps:
Once you grasp these steps, then moving on to the power recurrence should make much more sense to you.