w3resource

Power Calculation with Recursion in R

R Programming: Control Structure Exercise-17 with Solution

Write a R program function to calculate the power of a number using recursion.

Sample Solution :

R Programming Code :

# Define a function to calculate the power of a number using recursion
power <- function(base, exponent) {
    # Base case: If exponent is 0, return 1
    if (exponent == 0) {
        return(1)
    } else if (exponent == 1) {
        return(base)
    } else {
        # Recursive case: Calculate power using recursion
        return(base * power(base, exponent - 1))
    }
}

# Test the function with example inputs
base <- 2
exponent <- 3
result <- power(base, exponent)

# Print the result
cat(base, "raised to the power of", exponent, "is:", result, "\n")

Output:

2 raised to the power of 3 is: 8           

Explatnaion:

In the exercise above,

  • The "power()" function takes two parameters: 'base' and 'exponent'.
  • It checks for the base case: if the 'exponent' is 0, it returns 1 (since any number raised to the power of 0 is 1).
  • If the 'exponent' is 1, it returns the 'base' itself.
  • If neither of the base cases is met, it calculates the power using recursion by multiplying the 'base' with the result of "power(base, exponent - 1)".
  • The function is then tested with an example input (base = 2 and exponent = 3), and the result is printed to the console.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Reverse number using While loop in R.
Next: Print ASCII values of Lowercase letters in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.