I have following code to divide one number recursively by another number:
#include <iostream>
using namespace std;
int divide(int number,int dividend){
int answer=0;
if (number>dividend || number==dividend ){
answer+=1;
return divide(number-dividend,dividend);
}
return answer;
}
int main(){
cout<<divide(20,5)<<endl;
return 0;
}
but unfortunately I get zero as answer. Do you see what is wrong?
Answer is a local variable. When you run this code, the first call to
dividecreates an instance of theanswervariable, sets it to 0, and then increments it to 1. Then, when you recursively calldivideagain, it creates a brand new instance of theanswervariable, sets that instance to 0, and then increments that instance to 1.In your final call to
divide, it creates a brand new instance of theanswervariable, sets that instance to 0, but since nownumber<=dividendit doesn’t increment it, and it returns that instance ofanswerwhich is 0.