English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program using recursion to calculate power

Comprehensive Collection of Kotlin Examples

In this program, you will learn to use recursive functions in Kotlin to calculate the power of a number.

Example: A program that uses recursion to calculate power

fun main(args: Array<String>) {
    val base = 3
    val powerRaised = 4
    val result = power(base, powerRaised)
    println("$base^$powerRaised = $result")
}
fun power(base: Int, powerRaised: Int): Int {
    if (powerRaised != 0)
        return base * return base - 1)
    else
        return 1
}

When the program is run, the output is:

3^4 = 81

In the above program, you use the recursive function power() to calculate the power.

In simple terms, the recursive function multiplies the base with itself to get the number of times to raise, that is:

3 * 3 * 3 * 3 = 81
Execution Steps
Iterationpower()powerRaisedresult
1power(3, 4)43 * result2
2power(3, 3)33 * 3 * result3
3power(3, 2)23 * 3 * 3 * result4
4power(3, 1)13 * 3 * 3 * 3 * resultfinal
Finallypower(3, 0)03 * 3 * 3 * 3 * 1 = 81

This is the equivalent Java code:Java Program Using Recursion to Calculate Power

Comprehensive Collection of Kotlin Examples