**Exercise:**

Write a Java Program to calculate the power of a number using recursion.

**Click Here to View the Solution!**

```
public class PowerCalculator {
public static void main(String[] args) {
int base = 4, powerRaised = 3;
int result = power(base, powerRaised);
System.out.printf("%d^%d = %d", base, powerRaised, result);
}
public static int power(int base, int powerRaised) {
if (powerRaised != 0)
return (base * power(base, powerRaised - 1));
else
return 1;
}
}
```

**Click Here to View the Output!**

4^3 = 64

**Click Here to View the Explanation!**

- This program employs recursion method to calibrate exponent of a given number.
- The function
`power()`

in the following program, accepts two arguments: ‘`base`

’ and ‘`powerRaised`

’. Variables are self explanatory here. - The function keeps taking product of the given number with itself, according to times provided by ‘
`powerRaised`

’ variable. - In the program the number whose power is to be calculated is ‘4’ as ‘base’ and the power to which it is to be raised is ‘3’. This implies that ‘4’ has to be multiplied with itself ‘3’ times.
- During first iteration, the return value for the function is “power(4, 3) = 4 *4*$ result 2
^{nd }iteration.” - In second iteration, the resultant value requires result from the upcoming iteration and so on.
- When the value of ‘powerRaised’ parameter becomes ‘0’, during 5
^{th }iteration, the ‘if’ statement becomes ‘false’ and ‘else’ statement is executed returning ‘1’. - The resultant value is of the following form (4*4*4= 64).