power using recursion

In this article, we are going to find power of given number using recursion in java.

Example:-

if num=2 and power=3, then the output will be 8.

steps:-

  • create a method with two arguments first is the number and second is the power.
  • if power=0, then return 1. this is the base for recursion to calculate power
  • else return number* same method with argument number and power-1.

java code to calculate power using recursion:-

package gangforcode;

import java.util.Scanner;

public class power {
    // power recursive method
    public static int power(int number, int power)
    {
        if(power==0)
            return 1;
        else
            return number*power(number,power-1);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the number");
        int number = sc.nextInt();
        System.out.println("enter the power");
        int power = sc.nextInt();

        System.out.println("result = "+power(number,power));
    }
}

Output:-

power using recursion

You can use the same approach to calculate the power using recursion in other programming languages like C, C++, Python, etc.

you can also refer following video to calculate power using recursion in java.

Leave a Comment