Program to calculate the power of a number using recursion in Kotlin
package com.includehelp.basic
import java.util.*
//function to calculate power using recursion
fun calPower(baseValue: Int, powerValue: Int): Int {
return if (powerValue != 0) baseValue * calPower(baseValue, powerValue - 1) else 1
}
//Main Function entry Point of Program
fun main(args: Array<String>) {
//Input Stream
val scanner = Scanner(System.`in`)
//input Base integer number
print("Enter Base Number : ")
val base: Int = scanner.nextInt()
//input Power integer number
print("Enter Power Number : ")
val power: Int = scanner.nextInt()
//Call function to Calculate Power using recursion
val res = calPower(base,power)
//Print Result
println("$base^$power = $res")
}
Output
Run 1:
Enter Base Number : 5
Enter Power Number : 3
5^3 = 125
-------
Run 2:
Enter Base Number : 6
Enter Power Number : 4
6^4 = 1296
-------
Run 3:
Enter Base Number : 7
Enter Power Number : 0
7^0 = 1
Program to calculate the power of a number using recursion in Kotlin
Output
need an explanation for this answer? contact us directly to get an explanation for this answer