Example: Program to calculate power using recursion
class Power {
public static void main(String[] args) {
int base = 3, powerRaised = 4;
int result = power(base, powerRaised);
System.out.println(base + "^" + powerRaised + "=" + result);
}
public static int power(int base, int powerRaised) {
if (powerRaised != 0) {
// recursive call to power()
return (base * power(base, powerRaised - 1));
}
else {
return 1;
}
}
}
Output
3^4 = 81
In the above program, you calculate the power using a recursive function power().
In simple terms, the recursive function multiplies the base with itself for powerRaised times, which is:
3 * 3 * 3 * 3 = 81
Iteration | power() | powerRaised | result |
---|---|---|---|
1 | power(3, 4) | 4 | 3 * result2 |
2 | power(3, 3) | 3 | 3 * 3 * result3 |
3 | power(3, 2) | 2 | 3 * 3 * 3 * result4 |
4 | power(3, 1) | 1 | 3 * 3 * 3 * 3 * resultfinal |
Final | power(3, 0) | 0 | 3 * 3 * 3 * 3 * 1 = 81 |
Also Read: