Java Program to calculate the power using recursion

In this program, you’ll learn to calculate the power of a number using a recursive function in Java.

Example: Program to calculate the power using recursion

  1. public class Power {
  2. public static void main(String[] args) {
  3. int base = 3, powerRaised = 4;
  4. int result = power(base, powerRaised);
  5. System.out.printf("%d^%d = %d", base, powerRaised, result);
  6. }
  7. public static int power(int base, int powerRaised) {
  8. if (powerRaised != 0)
  9. return (base * power(base, powerRaised - 1));
  10. else
  11. return 1;
  12. }
  13. }

When you run the program, the output will be:

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
Execution steps
Iterationpower()powerRaisedresult
1power(3, 4)43 * result2
2power(3, 3)33 * 3 * result3
3power(3, 2)23 * 3 * 3 * result4
4power(3, 1)13 * 3 * 3 * 3 * resultfinal
Finalpower(3, 0)03 * 3 * 3 * 3 * 1 = 81