1. Introduction
Calculating the power of a number refers to multiplying the number by itself a specified number of times. For instance, 2 raised to the power 3 (2^3) equals 2 * 2 * 2 = 8. In this tutorial, we will implement a Scala program to calculate the power of a number using both iterative and recursive methods.
2. Program Steps
1. Initialize the Scala environment.
2. Implement the iterative method to calculate the power of a number.
3. Implement the recursive method to calculate the power of a number.
4. Print the result of both methods.
5. Execute the program.
3. Code Program
object PowerCalculator {
def main(args: Array[String]): Unit = {
val base = 2
val exponent = 3
// Calculate power using iterative method
val iterativeResult = powerIterative(base, exponent)
println(s"$base raised to the power of $exponent (Iterative) = $iterativeResult")
// Calculate power using recursive method
val recursiveResult = powerRecursive(base, exponent)
println(s"$base raised to the power of $exponent (Recursive) = $recursiveResult")
}
// Iterative method to calculate power
def powerIterative(base: Int, exponent: Int): Int = {
var result = 1
for (_ <- 1 to exponent) {
result *= base
}
result
}
// Recursive method to calculate power
def powerRecursive(base: Int, exponent: Int): Int = {
if (exponent == 0) 1
else base * powerRecursive(base, exponent - 1)
}
}
Output:
2 raised to the power of 3 (Iterative) = 8 2 raised to the power of 3 (Recursive) = 8
Explanation:
1. We encapsulate our program within the PowerCalculator object.
2. In the main function, we declare our base number base and the exponent exponent.
3. The powerIterative method calculates the power of a number using a for-loop. It initializes a result variable to 1 and multiplies it by the base number for exponent times.
4. The powerRecursive method calculates the power of a number using recursion. The base case is when the exponent is 0, returning 1. Otherwise, it multiplies the base with a recursive call by decrementing the exponent.
5. We then call both methods and print the results. For our given sample (2^3), the output is 8 for both methods.
Comments
Post a Comment