{
System.out.println (base + " to the " + i + " power = " +
power(base, i));
}
public static double power(double baseNum, int exp)
{
if (exp == 0)
return 1;
else
return baseNum * power(baseNum, --exp);
}
Quick question, the method above called “power” somehow returns the solution to an answer when it returns “1”. So if I passed the parameters to calculate 2 ^ 5, RETURN 1 somehow turns into 32.0. What exactly is going on here? how does “1” become 32.0?
That code right there. When one of the
powerfunctions is returning 1, it actually was called by this. So it’s going to be like:And the
powerreturned 1, so:And baseNum would be 32.0 in that case.
Recursion.
Better explanation: http://pastebin.com/raw.php?i=dHTnSPuY (my comment begin with an @ sign)