Kotlin Program to Calculate the Power of a Number


In this article, we will understand how to calculate the power of a number. The calculate the power of a number is calculated using a loop and multiplying it by itself multiple times.

Below is a demonstration of the same −

Suppose our input is −

Number : 4
Exponent value : 5

The desired output would be −

The result is 1024

Algorithm

  • Step 1 − START

  • Step 2 − Declare three integer values namely baseValue, exponentValue and and myResult

  • Step 3 − Define the values

  • Step 4 − Using a while loop, multiply the input value with itself for n number of times where n is the exponent value. Store the result.

  • Step 5 − Display the result

  • Step 6 − Stop

Example 1

In this example, we will calculate the power of a number using a while loop. First, let us declare and initialize the required variables, including the base and exponent value.

val baseValue = 4
var exponentValue = 5
var myResult: Long = 1

Now, use a while loop to calculate the result i.e. the power of a number −

while (exponentValue != 0) {
   myResult *= baseValue.toLong()
   --exponentValue
}

Let us now see the complete example to calculate the power of a number −

fun main() { val baseValue = 4 var exponentValue = 5 var myResult: Long = 1 println("The baseValue value and the exponentValue are defined as $baseValue and $exponentValue respectively") while (exponentValue != 0) { myResult *= baseValue.toLong() --exponentValue } println("The result is: $myResult") }

Output

The baseValue value and the exponentValue are defined as 4 and 5 respectively
The result is: 1024

Example 2

In this example, we will calculate the power of a number −

fun main() { val baseValue = 4 var exponentValue = 5 println("The baseValue value and the exponentValue are defined as $baseValue and $exponentValue respectively") power(baseValue, exponentValue) } fun power(input1: Int, input2: Int) { val baseValue = input1 var exponentValue = input2 var myResult: Long = 1 while (exponentValue != 0) { myResult *= baseValue.toLong() --exponentValue } println("The result is: $myResult") }

Output

The baseValue value and the exponentValue are defined as 4 and 5 respectively
The result is: 1024

Updated on: 17-Oct-2022

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements