Recursion
Recursion
Figure 1: https://youtu.be/kepBmgvWNDw
In summary:
Function rec: Function Fact(n):
if base condition: if n==1 then
… return 1
else else
… recursive formula return n*Fact(n-1)
Practice problems: 2
Practice problems:
Instructions:
1. Do not adopt unfair means. 10 marks will be deducted from the final marks for
adopting unfair means.
2. No more than 40% marks for uncompilable codes.
6. Write a recursive program to find the sum of the elements of an array of size n.
7. Write a recursive program to find the products of the elements of an array of size n.
8. Write a recursive program to find the maximum of the elements of an array of size n.
9. Write a recursive program to find the minimum of the elements of an array of size n
10. Write a recursive program to find the average of the elements of an array of size n
11. Write a recursive program to count/print the odd/even numbers of an array of n
integers
12. Write a recursive program to print an array of size n in reverse order
13. Write a recursive program to print the even numbers in a given range.
Sample input Sample output
3 10 4 6 8 10
14. Write a recursive program to check if a given string is a palindrome or not.
20. Write a recursive program to solve the Tower of Hanoi problem for 𝑛 disks.
Sample
Sample output
input
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Move disk 3 from A to B
Move disk 1 from C to A
Move disk 2 from C to B
Move disk 1 from A to B
4 Move disk 4 from A to C
Move disk 1 from B to C
Move disk 2 from B to A
Move disk 1 from C to A
Move disk 3 from B to C
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
21. Write a recursive implementation of binary search in a sorted array.
22. Given a set of parentheses check if they are balanced or not using a recursive
function.
23. Write a recursive program to print all subsets of a set of 𝑛 elements.
24. Write a recursive program to print all subsequence of a string.
25. DFS
26. In-order, preorder, postorder
27. Print path from node to the root of a binary tree