You are on page 1of 12

Student Name

Fazeel Ahmad

Student Roll # INFT-18111027

Department Information Technology

Batch/Year/Section 2018-2022

For Lab. Instructor

Marks Signature

Course: Data Structures & Algorithms

Lab Instructor:
Ms. Humaira Anwer

Department of Computer Science & Information Technology

Khwaja Fareed University of Engineering


& Information Technology,
(KFUEIT)
Abu Dhabi Road,
Rahim Yar Khan.

29/05/2017
Lab Manual Recursion
#11

Lab Manual # 11
Recursion

KFUEIT Department of CS/IT


168
Objective
After performing this lab students would be able to:
1. Understand the basics of recursion.
2. Understand and implement various algorithms for recursive functions.
3. Implement the algorithm for towers of Hanoi recursively.
Recursion
Some computer programming languages allow a module or function to call itself. This
technique is known as recursion. In recursion, a function α either cal s itself directly or cal s a
function β that in turn cal s the original function α. The function α is cal ed recursive
function.

Example − a function cal ing itself.

int function(int value)

if(value < 1)

return;

function(value - 1);

cout<<value<<“ ”;

Output (Give output of the above example if value = 13)

Properties
A recursive function can go infinite like a loop. To avoid infinite running of recursive
function, there are two properties that a recursive function must have −

 Base criteria − There must be at least one base criteria or condition, such that, when
this condition is met the function stops calling itself recursively.
 Progressive approach − The recursive calls should progress in such a way that each
time a recursive call is made it comes closer to the base criteria.

Implementation
Many programming languages implement recursion by means of stacks. Generally, whenever
a function (caller) calls another function (callee) or itself as callee, the caller function
transfers execution control to the callee. This transfer process may also involve some data to
be passed from the caller to the callee.
This implies the caller function has to suspend its execution temporarily and resume later
when the execution control returns from the callee function. Here, the caller function needs to
start exactly from the point of execution where it puts itself on hold. It also needs the exact
same data values it was working on. For this purpose, an activation record (or stack frame) is
created for the caller function.

Fig. 12.1. Recursive Function Calls

This activation record keeps the information about local variables, formal parameters, return
address and all information passed to the caller function.

Analysis of Recursion
One may argue why to use recursion, as the same task can be done with iteration. The first
reason is, recursion makes a program more readable and because of latest enhanced CPU
systems, recursion is more efficient than iterations.

Fibonacci Series
Fibonacci series generates the subsequent number by adding two previous numbers.
Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be
taken 0, 1 or 1, 1 respectively.

Fibonacci series satisfies the following conditions −

Fn = Fn-1 + Fn-2
Hence, a Fibonacci series can look like this −

F8 = 0 1 1 2 3 5 8 13

or, this −
F8 = 1 1 2 3 5 8 13 21
Fibonacci Recursive Algorithm

void FIB (n)


Description: This algorithm generates Fibonacc i series up to the
entered number n.

1. START
2. CHECK if n = 0 then
a. return 1
3. ELSE CHECK if n = 1 then
a. return 1
4. ELSE
a. return (FIB(n-1) + FIB(n-2))
5. EXIT

Factorial
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all
positive integers less than or equal to n. For example,
5!=5*4*3*2*1=120.
The value of 0! is 1, according to the convention for an empty product.

So the rule is:

n! = n × (n−1)!
n n!
1 1 1 1
2 2×1 = 2 × 1! =2
3 3×2×1 = 3 × 2! =6
4 4×3×2×1 = 4 × 3! = 24
5 5×4×3×2× 1 = 5 × 4! = 120
6 etc etc

Fig. 12.2. Factorial Calculation


Factorial Recursive Algorithm

void FACT (n)


Description: This algorithm generates Factorial of the given number

1. START
2. CHECK if n = 0 then
a. return 1
3. ELSE
a. return (n * FACT(n-1))
4. EXIT
Towers of Hanoi
Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower) is a mathematical puzzle
which consists of three towers (pegs) and more than one rings is as depicted −

Fig. 12.3. Towers of Hanoi

These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one
sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.

Origins

The puzzle was invented by the French mathematician Édouard Lucas in 1883. There is a
story about an Indian temple in Kashi Vishwanath, which contains a large room with three time-
worn posts in it surrounded by 64 golden disks. Brahmin priests, acting out the command of
an ancient prophecy, have been moving these disks, in accordance with the immutable rules of
the Brahma, since that time. The puzzle is therefore also known as the Tower of Brahma
puzzle. According to the legend, when the last move of the puzzle is completed, the world will
end. It is not clear whether Lucas invented this legend or was inspired by it.

If the legend were true, and if the priests were able to move disks at a rate of one per second,
using the smallest number of moves, it would take them 264 − 1 seconds, or roughly 585
billion years to finish, which is about 42 times the current age of the Universe.

Solution
The puzzle can be played with any number of disks, although many toy versions have around
7 to 9 of them. The minimal number of moves required to solve a Tower of Hanoi puzzle is
2n − 1, where n is the number of disks.

Rules

The mission is to move all the disks to the last (3 rd) tower without violating the sequence of
arrangement. A few rules to be followed for Tower of Hanoi are −

1. Only one disk can be moved among the towers at any given time.
2. Only the "top" disk can be removed.
3. No large disk can sit over a small disk.

Pseudocode

The steps to follow are −

Step 1 − Move n-1 disks from BEG to aux


Step 2 − Move n th disk from BEG to END
Step 3 − Move n-1 disks from AUX to END
A recursive algorithm for Tower of Hanoi can be driven as follows –

Towers of Hanoi recursive Algorithm

void TOWER (int n, char Beg, char Aux, char End)

Description: This algorithm solves tower of Hanoi Problem for the


n number of disks.

1. START
2. CHECK if n = 1 THEN
a. PRINT BEG → END
3. ELSE
a. CALL TOWER (n - 1, Beg, End, Aux)
b. CALL TOWER (1, Beg, Aux, End)
c. CALL TOWER (n - 1, Aux, Beg, End)
4. EXIT

LAB TASK 01

1. Write a single C++ code to implement factorial and Fibonacci series recursive
functions. The program must ask user to enter a number and then it display factorial and
Fibonacci series of that number.

Code Area

#include <iostream>
using namespace std;

int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;

cout << "Enter the number of terms: ";


cin >> n;

cout << "Fibonacci Series: ";

for (int i = 1; i <= n; ++i) {


// Prints the first two terms.
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;

cout << nextTerm << ", ";


}
return 0;
}
LAB TASK 02
2. Write C++ code to solve tower of Hanoi problem.

Code Area

// C++ recursive function to


// solve tower of hanoi puzzle
#include <bits/stdc++.h>
using namespace std;

void towerOfHanoi(int n, char from_rod,


char to_rod, char aux_rod)
{
if (n == 1)
{
cout << "Move disk 1 from rod " << from_rod <<
" to rod " << to_rod<<endl;
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
cout << "Move disk " << n << " from rod " << from_rod <<
" to rod " << to_rod << endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}

// Driver code
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}

// This is code is contributed by rathbhupendra


LAB TASK 03

3. Suppose there are 4 disks in the tower of Hanoi. Provide Sequence of moves by creating
Hanoi tree.

#include <bits/stdc++.h>
#define lli long long
using namespace std;
lli dp[202];
int main()
{
int t,n;
lli x,y;
cin >> t;
assert(t<=10);
while ( t-- ) {
cin >> n;
assert(n<=200);
vector < pair<lli,lli> > v;
for ( int i = 0; i < n; i++ ) {
cin >> x >> y;
assert(x<=1000000000);
assert(y<=1000000000);
v.push_back(make_pair(x,y));
}
sort(v.begin(),v.end());
dp[0] = v[0].second;
lli ans = v[0].second;
for ( int i = 1; i < n; i++ ) {
dp[i] = v[i].second;
for ( int j = 0; j < i; j++ ) {
if ( v[i].second > v[j].second && v[i].first > v[j].first ) dp[i] = max(dp[i], dp[j]
+v[i].second);
}
ans = max(ans, dp[i]);
}
cout << ans << endl;
}
return 0;
}

You might also like