w3resource

Kotlin recursive function: Calculate the power of a number


Write a Kotlin recursive function to calculate the power of a number.


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should understand these concepts:

  • Recursion: Recursion is a technique where a function calls itself to break down a problem into smaller subproblems. It requires a base case to prevent infinite recursion.
  • Exponentiation: Raising a number to a power means multiplying it by itself multiple times. For example, 34 = 3 × 3 × 3 × 3 = 81.
  • Base Case in Recursion: When the exponent is 0, the function should return 1 because any number raised to the power of 0 is 1.
  • Recursive Case: The recursive function should multiply the base by the result of the function called with the exponent reduced by 1.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Define a function that takes a base and an exponent as input.
  • Hint 2: Use an if condition to check if the exponent is 0 (base case).
  • Hint 3: If the exponent is greater than 0, multiply the base by the function called with the exponent reduced by 1.
  • Hint 4: Continue recursion until the exponent reaches 0, and return the computed value.

Sample Solution:

Kotlin Code:

fun calculatePower(base: Int, exponent: Int): Int {
    return if (exponent == 0) {
        1
    } else {
        base * calculatePower(base, exponent - 1)
    }
}

fun main() {
    val base = 3
    val exponent = 4
    val result = calculatePower(base, exponent)
    println("$base raised to the power of $exponent: $result")
}

Sample Output:

3 raised to the power of 4: 81

Explanation:

In the "calculatePower()" function, we check if the exponent is 0. If it is, we return 1 since any number raised to the power of 0 is 1. Otherwise, we recursively call the "calculatePower()" function with the same base and decrement the exponent by 1 in each recursion. We multiply the base with the result of the recursive call. This process continues until the exponent becomes 0, and we eventually get the power of the base.

When we run the program with base set to 3 and exponent set to 4, it will calculate and print the result of 3 raised to the power of 4, which is 81.

Kotlin Editor:


Previous: Sum of digits of a positive integer.
Next: Calculate the sum of array elements.

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.