0% found this document useful (0 votes)
8 views

Recursion and Fibonacci Series

Uploaded by

Maniacal Danger
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Recursion and Fibonacci Series

Uploaded by

Maniacal Danger
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Recursion

Recursion
&
Fibonacci
Series
Recursion
A recursive function in C allows the programmer to call
the same function within itself.
Recursion
Function to calculate Factorial using iteration
long factorial(int n)
{
int i;
long fact = 1;
for( i= 1 ; i <= n ; i++ )
fact = facr*i;
return ( fact );
}
Recursion
There are a wide variety of problems that we can solve
using recursion such as to compute the factorial of a
number, to find the Fibonacci series in a given range,
the various kinds of tree traversals and the famous
Tower of Hanoi problem.

Pretend for a minute that you do not have while loops


or for loops.
How would you compute the factorial of a n number?
Recursion
The iterative definition of the factorial of X, denoted as X! ,
is the product of X * ( X - 1 ) * ( X - 2 ) * . . . * 1.

X! can also be defined recursively as:


X! = 1 for all X less than or equal to 1
X! = X * ( X - 1 )! for all X greater than 1

This can be programmed as:


long int factorial( int X ) {
if( X <= 1 )
return 1;
return X * factorial( X - 1 );
}
Recursion
Recursion
Here we are trying to find 5! (five factorial). The factorial
function is defined as the product of all positive integers
less than or equal to its argument.

The first condition states: “if the parameter passed is less


than or equals 1 ( or 0 or 1), we will exit and return 1”.

Next, the recursive case states:

“If the parameter is not 0 or 1, then we will pass value of X


times the return value of calling this function again with X-1
as its argument”.
Recursion
So if we call factorial(0), the function returns 1 and never
hits the recursive case.
The same holds for factorial(1).
This called base case
A case for which the answer is known (and can be
expressed without recursion) is called a base case.
• Recursive case
Each recursive algorithm must have at least one. base case,
as well as the general (recursive) case
In the above example return X * factorial ( X-1) is the
recursive case.
Recursion
Steps :
1. The execution stack places factorial() with 5 as the argument
passed. The base case is false, so enter the recursive condition.
2. The execution stack places factorial() a second time with X-1 = 4 as
argument. Base case is false, enter recursive condition.
3. The execution stack places factorial() a third time with X-1 (4–1) = 3
as argument. Base case is false, enter recursive condition.
4. The execution stack places factorial() a fourth time with X-1(3–1) = 2
as argument. Base case is false, enter recursive condition.
The execution stack places factorial() a fifth time with X-1 (2–1) = 1 as
argument.
Now the base case is true, so return 1.

At this point, we have decreased the argument by one on each function


call until we reach a condition to return 1.
Recursion
5. From here the last execution context completes,
X ===1, so that function returns 1.
6. Next X === 2, so the return value is 2. (1×2).
7. Next X === 3, so the return value is 6, (2×3).

So far we have 1×2×3.


8. Next, X === 4, (4×6). 24 is the return value to the next
context.
9. Finally, X === 5, (5×24) and we have 120 as the final
value.
Recursion
There can me more than one base cases
Example:
Recursion
Recursion
Fibonacci
Series
Fibonacci Series
Thanks to one medieval man's obsession with rabbits, we have a
sequence of numbers that reflect various patterns found in
nature.

In 1202, Italian mathematician Leonardo Pisano (also known as


Fibonacci, meaning "son of Bonacci") pondered the question:
Given optimal conditions, how many pairs of rabbits can be
produced from a single pair of rabbits in one year?

This thought experiment dictates that the female rabbits always


give birth to pairs, and each pair consists of one male and one
female.
Fibonacci Series
Think about it -- two newborn rabbits are placed in a fenced-in
yard and left to, well, breed like rabbits.

Rabbits can't reproduce until they are at least one month old, so
for the first month, only one pair remains.

At the end of the second month, the female gives birth, leaving
two pairs of rabbits. When month three rolls around, the original
pair of rabbits produce yet another pair of newborns while their
earlier offspring grow to adulthood.

This leaves three pairs of rabbit, two of which will give birth to
two more pairs the following month.
Fibonacci Series
Fibonacci Series
The order goes as follows:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 and on to infinity. Each
number is the sum of the previous two.
This series of numbers is known as the Fibonacci numbers or
the Fibonacci sequence. The ratio between the numbers
(1.618034) is frequently called the golden ratio or golden
number.

At first glance, Fibonacci's experiment might seem to offer little


beyond the world of speculative rabbit breeding.

But the sequence frequently appears in the natural world -- a


fact that has intrigued scientists for centuries.
Fibonacci Series
We observe that many of the natural things follow the Fibonacci
sequence.

It appears in biological settings such as


• branching in trees,
• phyllotaxis (the arrangement of leaves on a stem),
• the fruit sprouts of a pineapple,
• the flowering of an artichoke,
• an uncurling fern and the arrangement of a pine cone's bracts etc.

Applications of Fibonacci numbers include computer algorithms such


as the Fibonacci search technique and the Fibonacci heap data
structure, and graphs called Fibonacci cubes used for
interconnecting parallel and distributed systems.
Recursive function for Fibonacci Numbers
The Fibonacci numbers are the numbers in the following integer
sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

In mathematical terms, the sequence Fn of Fibonacci numbers is


defined by the recurrence relation

Fn = Fn-1 + Fn-2

with base cases

F0 = 0 and F1 = 1.
Recursive function for Fibonacci Numbers

int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
Recursive function for Fibonacci Numbers
Non recursive function Fibonacci Numbers
void fib(int n)
{
int a = 0, b = 1, c, count = 3;
if(n == 1)
printf("0");
else if(n == 2)
printf("0 1");
else
{
printf("0 1 ");
while(count <= n)
{
c = a + b;
printf("%d ", c);
a = b;
b = c;
count++;
}
}
}
Contd…
Tower of Hanoi
Contd…
The disks on one rod in decreasing order of size from
bottom to top.
The goal of the puzzle is to move the entire initial stack
to another rod while following three simple rules:
A disk cannot be placed on top of another disk whose
size is smaller.
Only one disk can be moved at a time In each move,
we must take the uppermost disk from one of the
stacks and move it on top of another stack or to an
empty rod.
Source: hackerearth.com
Contd…
Contd…

Step 1: Move Disk A to Disk C


Contd…

Step 2: Move the second smallest disk to rod B


Contd…

Step 3: Move the smallest disk to rod B


Contd…

Step 4: We want the largest disk at the bottom of rod C


so our next move is to move it there.
Contd…

Step 5 : Now we need to move the stack on rod B to rod


C. To do this we can first move the smallest disk to rod A.
Contd…

Step 6: Then we can move the second smallest disk to rod C


Contd…

Step 7 : Finally, we move the smallest disk to rod C as


well and we are done!
Why this problem can be solved using Recursion?

If you take a look at those steps you can see that we


were doing the same task multiple times — moving
disks from one stack to another. We can call these
steps inside steps recursion.

The algorithm or the working procedure, which is to be


repeated for a finite number of steps, is illustrated
below:
Contd…

A, B and C are rods or pegs and n is the total number of discs, 1 is the largest
disk and 5 is the smallest one.
– Move n-1 discs from rod A to B which causes disc n alone in on the rod A
– Transfer the disc n from A to C
– Transfer n-1 discs from rod B to C so that they sit over disc n
Solution of Tower of Hanoi with a single disk is
very simple.
Contd… If there are Two disk given disk 1 and
disk 2
Contd… 2nd move is
Contd… 3rd step is

Movement of small number of disk from source to destination is very


simple and trivial.
If there are more than 3 disks , the problem becomes more complex.
Contd… Let's consider movements of 3 disk.

Actually we have to move 2 discs at a time.


But here I have written move 2 discs from A to C.
How to move one disk from one rod to another rod is already discussed in the
previous example.
So, move 2 discs from A to B using C is a recursive statement.
Contd… Here, we are talking moving two discs at a time.
Contd… Next step is move disc A to C
Contd… Next move 2 discs from B to C using A.
Again this is a Recursive Step
Contd… "If there are n disks the above steps can be
written as "
Contd… Recursive algorithm for Tower of Hanoi can
be written as
Contd… Figure comparison of the steps with the
algorithm

You might also like