w3resource

Scala Power Calculator: Calculate the Power of a Number


Write a Scala function to calculate the power of a number.


Pre-Knowledge (Before you start!)

  • Basic Scala Syntax: Familiarity with writing and running Scala programs.
  • Variables in Scala: Knowledge of declaring and initializing variables using var for mutable values.
  • While Loops: Understanding how to use while loops for repetitive tasks.
  • Arithmetic Operations: Ability to perform multiplication and update variables during program execution.
  • Function Parameters: Awareness of passing arguments to functions and using them within the function body.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Function: Create a function named "calculatePower" that takes two parameters: "base" (a Double) and "exponent" (an Int). The function should return a Double representing the result of raising the base to the power of the exponent.
  • Initialize Variables: Declare a variable to store the result, starting with 1.0, and another variable to track the current iteration count.
  • Use a While Loop: Use a while loop to multiply the base by itself repeatedly for the number of times specified by the exponent. Update the result and iteration count in each step.
  • Return the Result: After the loop completes, return the calculated result.
  • Call the Function: In the main method, test the "calculatePower" function by passing different values for the base and exponent, such as 3.0 and 4.
  • Display the Output: Use println() to print the result in a readable format, including the base, exponent, and calculated power in the output message.
  • Test with Different Values: Change the input values to verify the program works for various cases, including edge cases like negative exponents or a base of 0.
  • Common Errors to Avoid:
    • Forgetting to initialize the result variable correctly, leading to incorrect calculations.
    • Misplacing the loop logic, causing infinite loops or incorrect results.
    • Not handling edge cases like negative exponents, which may require additional logic to compute reciprocals.

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?



Follow us on Facebook and Twitter for latest update.