Java Program to Calculate the Power of a Number Using Recursion

You are currently viewing Java Program to Calculate the Power of a Number Using Recursion

Java program to calculate the power of a number using recursion

// Java program to calculate the power of a number 
// using the recursion

import java.util.*;

public class Main {
  public static long getPower(int base, int power) {
    long res = 1;

    if (power > 0)
      res = base * (getPower(base, power - 1));

    return res;
  }

  public static void main(String[] args) {
    Scanner X = new Scanner(System.in);
    int base = 0;
    int power = 0;
    long result = 0;

    System.out.printf("Enter base: ");
    base = X.nextInt();

    System.out.printf("Enter power: ");
    power = X.nextInt();

    result = getPower(base, power);
    System.out.printf("Result is: " + result);
  }
}

Output

Enter base: 3 
Enter power: 3
Result is: 27

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply