In this program, you'll learn to calculate the power of a number using a recursive function in Kotlin.

```
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 * power(base, powerRaised - 1)
else
return 1
}
```

When you run the program, the output will be:

3^4 = 81

In the above program, you calculate the power using a recursive function power().

In simple terms, the recursive function multiplies the base with itself for powerRaised times, which is:

3 * 3 * 3 * 3 = 81

Iteration | power() | powerRaised | result |
---|---|---|---|

1 | power(3, 4) | 4 | 3 * result_{2} |

2 | power(3, 3) | 3 | 3 * 3 * result_{3} |

3 | power(3, 2) | 2 | 3 * 3 * 3 * result_{4} |

4 | power(3, 1) | 1 | 3 * 3 * 3 * 3 * result_{final} |

Final | power(3, 0) | 0 | 3 * 3 * 3 * 3 * 1 = 81 |

Here's the equivalent Java code: Java Program to calculate power using recursion

It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:

**Disabling AdBlock on Programiz. We do not use intrusive ads.**

or

Donate on Paypal
By using Programiz, you agree to use cookies as stated in our Privacy policy Continue