Kotlin Program to Calculate Power of Number With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

In this post, we will go through Kotlin program to calculate power (b) of given number (a).

For example,

Case 1 –
Input:
a = 4, b = 5

Output:
1024

Case 2 –

Input:
a = 2, b = 3

Output:
8

There are several ways using which you can find power of number.

  1. Using while Loop
  2. Using for Loop
  3. Using pow Function

1. Calculate Power of Given Number (While Loop)

Sourcecode –

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter a:")
    val a = read.nextInt()

    println("Enter b:")
    var b = read.nextInt()

    var res = 1
    while (b != 0) {
        res *= a
        b--
    }

    println("Power = $res")
}

When you run the program, output will be

Enter a:
12
Enter b:
3
Power = 1728
Explanation:

We calculated power by multiplying a by b times using while loop in Kotlin

2. Calculate Power of Given Number (for Loop)

Sourcecode –


import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter a:")
    val a = read.nextInt()

    println("Enter b:")
    val b = read.nextInt()

    var res = 1
    for(i in 1..b) {
        res *= a
    }

    println("Power = $res")
}

When you run the program, output will be

 Enter a:
 10
 Enter b:
 5
 Power = 100000
 
Explanation:

We calculated power by multiplying a by b times using for loop in Kotlin

3. Calculate Power Using pow function

Now, we will use pow function to calculate power (b) of number (a).

import java.util.*
import kotlin.math.pow

fun main() {

    val read = Scanner(System.`in`)

    println("Enter a:")
    val a = read.nextInt()

    println("Enter b:")
    val b = read.nextInt()

    val res = a.toDouble().pow(b)

    println("Power = $res")
}

 Enter a:
 12
 Enter b:
 5
 Power = 248832.0
 

Here, we used pow function to calculate power of number.

Thus, we went through different kotlin program to calculate power (b) of given number (a).

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners