Java program to calculate the power of a number using recursion

Given a number, we have to calculate the power of it using recursion.
Submitted by Nidhi, on June 01, 2022

Problem Solution:

In this program, we will read the base and its power from the user and then we will calculate the power of the input number using recursion.

Program/Source Code:

The source code to calculate the power of a number using recursion is given below. The given program is compiled and executed successfully.

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

Explanation:

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main. The Main class contains two static methods getPower(), main(). The getPower() is a recursive method that calculates the power of a specified number and returns the result to the calling method.

The main() method is the entry point for the program. Here, we read base and power from the user and called the getPower() method to get the result of power and printed the result.

Java Recursion Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.