Scala Power Calculator: Calculate the Power of a Number
Scala Function Exercise-7 with Solution
Write a Scala function to calculate the power of a number.
Sample Solution:
Scala Code:
object PowerCalculator {
def calculatePower(base: Double, exponent: Int): Double = {
var result = 1.0
var i = 0
while (i < exponent) {
result *= base
i += 1
}
result
}
def main(args: Array[String]): Unit = {
val base = 3.0
val exponent = 4
val result = calculatePower(base, exponent)
println(s"The result of $base raised to the power of $exponent is: $result")
}
}
Sample Output:
The result of 3.0 raised to the power of 4 is: 81.0
Scala Code Editor :
Previous: Find the maximum element.
Next: Check if a number is even.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/function/scala-function-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics