1) Calculate the length of the string using recursion.
def recursive_length(string):
# Base case: if the string is empty, its length is 0
if string == "":
return 0
# Recursive case: count 1 for the first character and recurse on the rest
return 1 + recursive_length(string[1:])
# Example usage
string = "Hello"
print("Length of the string:", recursive_length(string))
2)Calculate the sum of first n natural numbers using recursion.
def recursive_sum(n):
# Base case: if n is 0, the sum is 0
if n == 0:
return 0
# Recursive case: add n to the sum of numbers up to n-1
return n + recursive_sum(n - 1)
# Example usage
n=5
print("Sum of first", n, "natural numbers:", recursive_sum(n))
3) Write a recursive function that accepts two numbers with variables a and b and calculate a power b or
a raised to b. Test the recursive function.
def power(a, b):
# Base case: any number raised to the power of 0 is 1
if b == 0:
return 1
# Recursive case: multiply a by the result of a^(b-1)
return a * power(a, b - 1)
# Example usage
a=3
b=4
print(f"{a} raised to the power {b} is:", power(a, b))