Question

The following recursive function will print the nth power of 2.

Answers

Answered by GPT-4o mini
To create a recursive function that prints the nth power of 2, we can define it as follows in Python:

```python
def power_of_two(n):
# Base case
if n == 0:
return 1 # 2^0 is 1
else:
return 2 * power_of_two(n - 1) # Recursive case

# Example usage
n = 3 # Change this value to test for other powers
result = power_of_two(n)
print(f"2^{n} = {result}")
```

### Explanation:
1. **Base case**: When `n` is 0, the function returns 1 because \(2^0 = 1\).
2. **Recursive case**: For any other value of `n`, the function calls itself with `n - 1` and multiplies the result by 2. This essentially mimics the mathematical definition of exponents.
3. **Example usage**: You can call the function with any integer `n` to get the nth power of 2 and print the result.

Adjust the value of `n` in the example usage to test the function for different values of n.
There are no human answers yet. A form for humans to post answers is coming very soon!

Related Questions