SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Recursion
Exercise:
Programming Exercises
Question:7 | ISBN:9780132576376 | Edition: 2

Question

Recursive Power Method
Design a function that uses recursion to raise a number to a power. The function should
accept two arguments: the number to be raised and the exponent. Assume that the exponent
is a nonnegative integer

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Recursive Power Methdo using recursion program code:

def power(base, exponent):
    """
    Recursive function to raise a number to a power.

    Arguments:
    - base: The number to be raised.
    - exponent: The nonnegative integer exponent.

    Returns:
    - The result of raising base to the power of exponent.
    """

    # Base case: If exponent is 0, return 1 (any number raised to 0 is 1).
    if exponent == 0:
        return 1
    
    # Recursive case: Multiply base with the result of raising base to (exponent - 1).
    # This effectively reduces the exponent by 1 with each recursive call.
    return base * power(base, exponent - 1)


# Test the function
base = 2
exponent = 5
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")

Executed Output:

def power(base, exponent):
    """
    Recursive function to raise a number to a power.

    Arguments:
    - base: The number to be raised.
    - exponent: The nonnegative integer exponent.

    Returns:
    - The result of raising base to the power of exponent.
    """

    # Base case: If exponent is 0, return 1 (any number raised to 0 is 1).
    if exponent == 0:
        return 1
    
    # Recursive case: Multiply base with the result of raising base to (exponent - 1).
    # This effectively reduces the exponent by 1 with each recursive call.
    return base * power(base, exponent - 1)


# Test the function
base = 2
exponent = 5
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")

Executed Output:

2 raised to the power of 5 is: 32

 

0 0

Discussions

Post the discussion to improve the above solution.