Reputation: 2066
Is it possible to create a recursive method that takes a single int as a parameter and returns the passed int to the power of 10?
this is what I have so far, but I get StackOverFlow error:
public static int exponent(int baseNum) {
return baseNum * exponent(baseNum);
}
Upvotes: 0
Views: 1981
Reputation: 11317
You forgot to tell the recursive function when to stop recursing. It'll just go forever, which is why you get a stack error.
public static int exponent(int baseNum, int exp) {
if (exp == 0)
return 1;
else
return baseNum * exponent(baseNum, --exp);
}
Now you can get 32^10 by calling:
exponent(32, 10);
And if you want a specialized function to raise a number to the power of ten then you can overload the exponent method:
public static int exponent(int baseNum) {
return exponent(baseNum, 10);
}
Only works with exponent values >= 0, of course.
Upvotes: 2