Kotlin recursive function: Calculate the power of a number
Kotlin Function: Exercise-2 with Solution
Write a Kotlin recursive function to calculate the power of a number.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/recursion-function/kotlin-recursion-function-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics