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 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
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

Leave a Reply