Lab 03
Lab 03
Note:
Lab manual cover following below recursion topics
{Base Condition, Direct and Indirect Recursion, Tailed Recursion, Nested Recursion,
Backtracking}
Maintain discipline during the lab.
Just raise hand if you have any problem.
Completing all tasks of each lab is compulsory.
Get your lab checked at the end of the session.
Sample Code
int Funct(int n)
{ if (n < = 1) // base case return 1;
else
return Funct (n-1);
}
Key Points: In the above example, base case for n < = 1 is defined and larger value of number
can be solved by converting to smaller one till base case is reached.
Task-1:
a. Generate the following sequence with recursive approach
1 , 3 , 6 , 10 , 15 , 21 , 28 . . . .
b. Generate the following sequence with recursive approach
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 . . .
Task 3:
Sort The Unsorted Numbers with both tail recursive and Normal recursive approach
Sample Input and Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Nested Recursion
Sample Code
#include <iostream>
using namespace std;
int fun(int n)
{
if (n > 100)
return n - 10;
return 0;
}
Task 4:
Dry run the outputs of the upper code in order to find out how the recursive calls are made.
Make a stack and visualize the functionality of stack in the case of recursion on paper.
Backtracking
Sample Pseudocode
A Maze is given as N*N binary matrix of blocks where source block is the upper left most
block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1].
A rat starts from source and has to reach the destination. The rat can move only in two
directions: forward and down.
In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in
the path from source to destination.