Write a Kotlin Program to Calculate the Power of a Number

In Kotlin, you can easily calculate the power of a number using the pow function from the kotlin.math package.

Here’s how you can create a program to calculate the power of a number in Kotlin:

import kotlin.math.pow

fun main() {
    val base = 2.0 // Base number
    val exponent = 3 // Exponent

    val result = base.pow(exponent.toDouble()) // Calculating power using pow() function

    println("$base raised to the power of $exponent is $result")
}

In this Kotlin program, you first import the pow function from the kotlin.math package.

We then define the base number and exponent as variables.

We will then use the pow function to calculate the power of the base number raised to the exponent.

Finally, we can print the result to the console using a formatted string.

We can modify this program to accept user input for the base number and exponent as follows:

import kotlin.math.pow

fun main() {
    print("Enter the base number: ")
    val base = readLine()!!.toDouble()

    print("Enter the exponent: ")
    val exponent = readLine()!!.toInt()

    val result = base.pow(exponent.toDouble())

    println("$base raised to the power of $exponent is $result")
}

In this modified Kotlin program, you can use the readLine() function to accept user input for the base number and exponent.

We can then convert the input to the appropriate data type using the toDouble() and toInt() functions.

We will then use the pow function to calculate the power and print the result to the console.