w3resource

Java Recursive Method: Calculate Base to Power

Java Recursive: Exercise-5 with Solution

Write a Java recursive method to calculate the exponentiation of a number (base) raised to a power (exponent).

Sample Solution:

Java Code:

public class ExponentiationCalculator {

  public static double calculateExponentiation(double base, int exponent) {
    // Base case: any number raised to the power of 0 is 1
    if (exponent == 0) {
      return 1;
    }

    // Recursive case: multiply the base with the exponentiation of (base, exponent-1)
    return base * calculateExponentiation(base, exponent - 1);
  }

  public static void main(String[] args) {
    double base = 3.5;
    int exponent = 4;
    double result = calculateExponentiation(base, exponent);
    System.out.println(base + " raised to the power of " + exponent + " is: " + result);
  }
}

Sample Output:

3.5 raised to the power of 4 is: 150.0625

Explanation:

In the above exercises -

The "calculateExponentiation()" method follows the recursive definition of exponentiation. It has two cases:

  • Base case: If the exponent is 0, it returns 1. This is because any number raised to the power of 0 is equal to 1.
  • Recursive case: For any positive exponent "exponent", it multiplies the base with the exponentiation of the same base raised to the power of exponent-1. This process is repeated recursively until the exponent reaches 0.

In the main() method, we demonstrate the calculateExponentiation() method by calculating the exponentiation of a base number (3.5) raised to a power (4) and printing the result.

Flowchart:

Flowchart: Java  recursive Exercises: Calculate Base to Power.

Java Code Editor:

Java Recursive Previous: String palindrome detection.
Java Recursive Next: Reverse a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.