02. Algo Lab - Recursion
02. Algo Lab - 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)
If STYLEREF “Heading 1” Simulation of a recursive function:<> “Error*” “ STYLEREF PAGE \*
“Heading 1” Simulation of a recursive function:""Add a heading to your MERGEFO
document""Simulation of a recursive function: RMAT 2
Why Stack Overflow error occurs in recursion?
If the base case is not reached or not defined, then the stack overflow problem may
arise. In the following code, Fact(5) or Fact(1) will cause stack overflow.
Function Fact(n):
if n==10 then
return 10
else
return n*Fact(n-1)
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.
Sampl
Sample output
e 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 subsequences of a string.
25. DFS
26. In-order, preorder, postorder
27. Print path from node to the root of a binary tree