Java program to find the power of a number using recursion

Java program to find the power of a number using recursion:

This post will show you how to find the power of a number using a recursive function in Java. The program will take the base and power values as inputs from the user to calculate the power.

Recursive function:

In simple word, a recursive function calls itself. Normally, we use a recursive function with a value to find a result. It calls itself again and again with a new value and it stops at a specific value.

For example,

int getSum(int no){
    if(no == 0) return 0;
    return no + getSum(no - 1);
}
  • The getSum is a recursive function and it can find the sum of all numbers from 1 to no.
  • It returns no + getSum(no - 1), i.e. it calls itself again with no - 1.
  • This will return (no - 1) + getSum(no - 1 - 1). So, the final return will be no + (no - 1) + getSum(no - 1 - 1). It will keep calling itself again and again until the value of no become 0.
  • It will return 0 if no is zero, i.e. the recursion will stop.

Recursive way to find the power of a number:

If n is the number and p is the power, the power of the number n can be found by multiplying n to itself for p number of times. We can use a recursive function to find that.

  • The function will take the number and the power values as the parameters.
  • On each recursive call, it will decrement the value of the power by one. It will return the result of multiplying itself with the result of its recursive call.
  • The recursion will stop once the power become 0.

Below is the complete program:

import java.util.Scanner;

class Main {
    static int findPower(int base, int power) {
        if (power == 0) return 1;
        return base * findPower(base, power - 1);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int base, power;

        System.out.println("Enter the base: ");
        base = scanner.nextInt();

        System.out.println("Enter the power: ");
        power = scanner.nextInt();

        System.out.println(base + "^" + power + " = " + findPower(base, power));
    }
}

Here,

  • We created a Scanner object, scanner to read the user input values.
  • The integer variables base and power are used to store the base and power values.
  • It asks the user to enter the base and power. It uses the scanner object to read these values and assigns to the base and power integer variables.
  • The findPower method is used to find the power. It takes the base and power values as its parameters and returns the power.
  • It returns base * findPower(base, power - 1). On each step, it calls the findPower method recursively. The recursive calls stops and returns 1 when the power becomes 0.

If you run this program, it will print output as below:

Enter the base: 
3
Enter the power: 
4
3^4 = 81

Java power number recursion example

You might also like: