Exercises for Recursion
Beginner-Level Exercises
1. Factorial Calculation
○ Write a recursive function to calculate the factorial of a number.
Example Input: factorial(5)
Output: 120
2. Sum of Digits
○ Write a recursive function to find the sum of the digits of a
number.
Example Input: sum_digits(123)
Output: 6
3. Count Down
○ Write a recursive function to print numbers from n to 1.
Example Input: count_down(5)
Output: 5, 4, 3, 2, 1
4. Power Calculation
○ Write a recursive function to compute base^exponent.
Example Input: power(2, 4)
Output: 16
5. Check Palindrome
○ Write a recursive function to check if a string is a palindrome.
Example Input: is_palindrome("radar")
Output: True
Intermediate-Level Exercises
6. Fibonacci Sequence
○ Write a recursive function to calculate the nth Fibonacci
number.
Example Input: fibonacci(6)
Output: 8
7. Greatest Common Divisor (GCD)
○ Write a recursive function to find the GCD of two numbers using
Euclid's algorithm.
Example Input: gcd(48, 18)
Output: 6
8. Reverse a String
○ Write a recursive function to reverse a string.
Example Input: reverse("hello")
Output: "olleh"
9. Binary Search
○ Write a recursive implementation of the binary search algorithm.
Input: A sorted array and a target value.
Output: Index of the target value or -1 if not found.
10. Tower of Hanoi
○ Write a recursive function to solve the Tower of Hanoi problem
for n disks.
Input: tower_of_hanoi(3, "A", "C", "B")
Output: Steps to move all disks from peg A to peg C using peg
B as auxiliary.
Advanced-Level Exercises
11. Permutations of a String
○ Write a recursive function to generate all permutations of a
given string.
Example Input: permutations("abc")
Output: ["abc", "acb", "bac", "bca", "cab",
"cba"]
12. Recursive Sum
○ Write a recursive function to calculate the sum of all elements in
a list.
Example Input: recursive_sum([1, 2, 3, 4])
Output: 10
13. Path in a Maze
○ Write a recursive function to find a path through a maze
represented as a 2D grid. Cells marked 1 are open, and 0 are
blocked.
14. Recursive Flattening
○ Write a recursive function to flatten a nested list.
Example Input: flatten([1, [2, [3, 4]], 5])
Output: [1, 2, 3, 4, 5]
15. N-Queens Problem
○ Write a recursive function to solve the N-Queens problem,
where you place N queens on an N×N chessboard such that no
two queens threaten each other.