Scala program to find the power of a number using recursion

1. Introduction

Calculating the power of a number is a fundamental operation in mathematics. For instance, 3 raised to the power of 4 (3^4) is 81. In this post, we will walk through a Scala program that computes the power of a number using a recursive approach.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define the base and exponent values.

4. Implement a recursive function to compute the power.

5. Invoke the function and display the result.

6. Execute the program.

3. Code Program

object PowerCalculatorApp {
  def main(args: Array[String]): Unit = {
    // Define base and exponent
    val base = 3
    val exponent = 4

    println(s"Computing $base raised to the power $exponent")

    // Calculate power using recursive function
    val result = power(base, exponent)
    println(s"\nResult: $result")
  }

  // Recursive function to compute power
  def power(base: Int, exponent: Int): Int = {
    if (exponent == 0) 1  // Base case: any number raised to 0 is 1
    else base * power(base, exponent - 1)  // Recursive call
  }
}

Output:

Computing 3 raised to the power 4
Result: 81

Explanation:

1. We commence with an object named PowerCalculatorApp. The main method inside this object acts as our program's starting point.

2. Inside the main function, we've defined two values: base and exponent, which represent the number we want to raise to a power and the power itself, respectively.

3. We then present the chosen base and exponent to the user.

4. The function named power calculates the power of the number. The function checks if the exponent is 0; if so, it returns 1 (since any number raised to the power of 0 is 1). Otherwise, it multiplies the base by the result of the power function called with the exponent decremented by 1. This recursive structure allows the program to calculate the power without using loops.

5. The main function calls the power method, procures the result, and displays it.

6. The output displays the computation of the base raised to its exponent and subsequently, the result.


Comments