Recursion Question for practice
1. Factorial of a Number
Write a recursive function to calculate the factorial of a non-negative integer n. (e.g.,
factorial(5) = 5 * 4 * 3 * 2 * 1 = 120)
2. Sum of First N Natural Numbers
Create a recursive function to compute the sum of the first n natural numbers. (e.g.,
sum(5) = 1 + 2 + 3 + 4 + 5 = 15)
3. Fibonacci Sequence
Write a recursive function to find the nth number in the Fibonacci sequence. (e.g., fib(6)
= 8, where sequence is 0, 1, 1, 2, 3, 5, 8)
4. Print Numbers from 1 to N
Use recursion to print all numbers from 1 to n in increasing order. (e.g., for n=5, print 1,
2, 3, 4, 5)
5. Print Numbers from N to 1
Write a recursive function to print all numbers from n to 1 in decreasing order. (e.g., for
n=5, print 5, 4, 3, 2, 1)
6. Sum of Digits
Create a recursive function to calculate the sum of digits of a number. (e.g., for 123,
output 1 + 2 + 3 = 6)
7. Power of a Number
Write a recursive function to compute a raised to the power b (i.e., a^b). (e.g., power(2,
3) = 8)
8. Count Digits in a Number
Use recursion to count the number of digits in a positive integer. (e.g., for 1234, output 4)
9. Reverse a String
Write a recursive function to reverse a given string. (e.g., for "hello", output "olleh")
10. Check if a String is a Palindrome
Create a recursive function to check if a given string is a palindrome. (e.g., "racecar"
returns true, "hello" returns false)
11. Sum of Elements in an Array
Write a recursive function to calculate the sum of all elements in an array. (e.g., for [1, 2,
3, 4], output 10)
12. Find Maximum Element in an Array
Use recursion to find the maximum element in an array. (e.g., for [3, 7, 2, 9, 1], output 9)
13. Print Even Numbers up to N
Write a recursive function to print all even numbers from 1 to n. (e.g., for n=6, print 2, 4,
6)
14. Calculate GCD (Greatest Common Divisor)
Create a recursive function to find the GCD of two positive integers using the Euclidean
algorithm. (e.g., gcd(48, 18) = 6)
15. Generate Binary Numbers
Write a recursive function to print all binary numbers of length n. (e.g., for n=2, print 00,
01, 10, 11)