Recursion and Fibonacci Series
Recursion and Fibonacci Series
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.
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.
Fn = Fn-1 + Fn-2
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…
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