Write a Kotlin Program to Calculate the Power using Recursion

In Kotlin, you can use recursion to calculate the power of a number.

Recursion is a technique where a function calls itself, and it can be a very useful approach for solving certain types of problems.

To calculate the power of a number using recursion, you can use the following steps:

  1. Define a function that takes two parameters, the base and the exponent.
  2. If the exponent is 0, return 1.
  3. If the exponent is 1, return the base.
  4. Otherwise, calculate the power of the base to the exponent-1 and multiply it by the base.
  5. Return the result.

Here is an example program that implements this algorithm:

fun power(base: Int, exponent: Int): Int {
return when {
exponent == 0 -> 1
exponent == 1 -> base
else -> base * power(base, exponent - 1)
}
}

fun main() {
val base = 2
val exponent = 5
val result = power(base, exponent)
println("$base raised to the power of $exponent is $result")
}

In this program, the power function takes two parameters, base and exponent, and returns an Int representing the result of base raised to the power of exponent.

The when expression is used to handle the different cases. If the exponent is 0, the function returns 1. If the exponent is 1, the function returns the base.

Otherwise, the function calculates the power of the base to the exponent-1 and multiplies it by the base.

In the main function, we define the base and exponent variables and call the power function to calculate the result. The println statement then outputs the result to the console.

That’s all there is to it! Recursion can be a powerful technique for solving certain types of problems, and it’s useful to have in your programming toolbox.