Power of a Number using Recursion in Java

Power of a Number using Recursion in Java

Here, in this page we will discuss the program to find power of a number using recursion in java programming language. We are given with two integers values base and power respectively. We need to print the value representing the base raise to its power. We will design the program using recursion and also discuss the approach using iteration as well.

Example :

  • Input : 5 3
  • Output : 125
  • Explanation : 53 = 125
Power of a Number using Recursion in Java

Method 1 (Using Recursion):

  • Create a recursive function say power(int base, int x)
  • Base condition : if(x==0) return 1.
  • Otherwise, return (base* power(base, x-1))
Power of a number

Java Code

Run
public class Main
{
  public static void main (String[]args)
  {
    int base = 5, x = 3;
    System.out.println ("Required Power is " + power (base, x));
  }
  //Recursive Function
  static int power (int base, int x)
  {
    if (x == 0)     //Base Condition
      return 1;
    return (base * power (base, x - 1));
  }
}
Output
Required Power is 125

Method 2 (Using Loop):

  • Create a function say power(int base, int x), that will return the integer value denoting the basex.
  • Create a variable say result = 1, that hold the basex.
  • Run a while loop that will terminate when x becomes 0.
  • Inside the loop set result = result * base.
  • After complete iteration return result.
Run
class Main {
    public static void main(String[] args) {
        int base = 5, x = 3;
        System.out.println("Required Power is " + power(base, x));
    }
    static int power(int base, int x) {
        int result = 1;
        while (x > 0) {
            result *= base;
            x--;
        }
        return result;
    }
}

Output

Required Power is 125

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

3 comments on “Power of a Number using Recursion in Java”


  • siddeshaob2001

    package recurtion;

    public class PowerofNumber {

    public static int Powerof(int base,int pow)
    {

    if(pow==0)
    {
    return 1;
    }

    return (base*Powerof(base, (pow-1)));
    }
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int n1=5;
    int n2=3;

    System.out.println(Powerof(n1,n2));

    }

    }


  • SRINJAY

    Using one argument-
    public static int rec(int n){
    if(p==1){
    return n;
    }
    p–;
    return n*rec(n);
    }