Category: Recursion

  • Fibonacci Series Using Recursion

    Fibonacci Series Using Recursion

    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

    For illustration purpose, Fibonacci of F8 is displayed as −

    Fibonacci Animation

    Fibonacci Iterative Algorithm

    First we try to draft the iterative algorithm for Fibonacci series.

    Procedure Fibonacci(n)
       declare f0, f1, fib, loop 
       
       set f0 to 0
       set f1 to 1<b>display f0, f1</b>for loop ← 1 to n
       
          fib ← f0 &plus; f1   
          f0 ← f1
          f1 ← fib
    
          <b>display fib</b>
       end for
    	
    end procedure
    

    Fibonacci Recursive Algorithm

    Let us learn how to create a recursive algorithm Fibonacci series. The base criteria of recursion.

    START
    Procedure Fibonacci(n)
       declare f0, f1, fib, loop 
       
       set f0 to 0
       set f1 to 1
       
       display f0, f1
       
       for loop ← 1 to n
       
          fib ← f0 &plus; f1   
          f0 ← f1
          f1 ← fib
    
          display fib
       end for
    
    END
    

    Example

    Following are the implementations of the above approach in various programming languages −

    CC++JavaPython

    #include <stdio.h>intfibbonacci(int n){if(n ==0){return0;}elseif(n ==1){return1;}else{return(fibbonacci(n-1)+fibbonacci(n-2));}}intmain(){int n =5;printf("Number is: %d", n);printf("\nFibonacci series upto number %d are: ", n);for(int i =0;i<n;i++){printf("%d ",fibbonacci(i));}}

    Output

    Number is: 5
    Fibonacci series upto number 5 are: 0 1 1 2 3 
  • Tower of Hanoi Using Recursion

    Tower of Hanoi

    Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one rings is as depicted −

    Tower 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.

    Rules

    The mission is to move all the disks to some another tower without violating the sequence of arrangement. A few rules to be followed for Tower of Hanoi are −

    • Only one disk can be moved among the towers at any given time.
    • Only the “top” disk can be removed.
    • No large disk can sit over a small disk.

    Following is an animated representation of solving a Tower of Hanoi puzzle with three disks.

    Tower Of Hanoi

    Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation shows that a puzzle with 3 disks has taken 23 – 1 = 7 steps.

    Algorithm

    To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with lesser amount of disks, say → 1 or 2. We mark three towers with name, sourcedestination and aux (only to help moving the disks). If we have only one disk, then it can easily be moved from source to destination peg.

    If we have 2 disks −

    • First, we move the smaller (top) disk to aux peg.
    • Then, we move the larger (bottom) disk to destination peg.
    • And finally, we move the smaller disk from aux to destination peg.
    Tower Of Hanoi with Two Disks

    So now, we are in a position to design an algorithm for Tower of Hanoi with more than two disks. We divide the stack of disks in two parts. The largest disk (nth disk) is in one part and all other (n-1) disks are in the second part.

    Our ultimate aim is to move disk n from source to destination and then put all other (n1) disks onto it. We can imagine to apply the same in a recursive way for all given set of disks.

    The steps to follow are −

    Step 1 − Move n-1 disks from source to aux
    Step 2 − Move nth disk from source to dest
    Step 3 − Move n-1 disks from aux to dest
    

    A recursive algorithm for Tower of Hanoi can be driven as follows −

    START
    Procedure Hanoi(disk, source, dest, aux)
    
       IF disk == 1, THEN
          move disk from source to dest             
       ELSE
          Hanoi(disk - 1, source, aux, dest)     // Step 1
          move disk from source to dest          // Step 2
          Hanoi(disk - 1, aux, dest, source)     // Step 3
       END IF
       
    END Procedure
    STOP
    

    Example

    Following are the implementations of this approach in various programming languages −

    CC++JavaPython

    #include <stdio.h>voidhanoi(int n,char from,char to,char via){if(n ==1){printf("Move disk 1 from %c to %c\n", from, to);}else{hanoi(n-1, from, via, to);printf("Move disk %d from %c to %c\n", n, from, to);hanoi(n-1, via, to, from);}}intmain(){int n =3;char from ='A';char to ='B';char via ='C';//calling hanoi() methodhanoi(n, from, via, to);}

    Output

    Move disk 1 from A to C
    Move disk 2 from A to B
    Move disk 1 from C to B
    Move disk 3 from A to C
    Move disk 1 from B to A
    Move disk 2 from B to C
    Move disk 1 from A to C
  • Recursion Algorithms

    Recursion

    Some computer programming languages allow a module or function to call itself. This technique is known as recursion. In recursion, a function α either calls itself directly or calls a function β that in turn calls the original function α. The function α is called recursive function.

    Example − a function calling itself.

    intfunction(int value){if(value <1)return;function(value -1);printf("%d ",value);}

    Example − a function that calls another function which in turn calls it again.

    intfunction1(int value1){if(value1 <1)return;function2(value1 -1);printf("%d ",value1);}intfunction2(int value2){function1(value2);}

    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.

    Activation Records

    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.

    Time Complexity

    In case of iterations, we take number of iterations to count the time complexity. Likewise, in case of recursion, assuming everything is constant, we try to figure out the number of times a recursive call is being made. A call made to a function is Ο(1), hence the (n) number of times a recursive call is made makes the recursive function Ο(n).

    Space Complexity

    Space complexity is counted as what amount of extra space is required for a module to execute. In case of iterations, the compiler hardly requires any extra space. The compiler keeps updating the values of variables used in the iterations. But in case of recursion, the system needs to store activation record each time a recursive call is made. Hence, it is considered that space complexity of recursive function may go higher than that of a function with iteration.

    Example

    Following are the implementations of the recursion in various programming languages −

    CC++JavaPython

    // C program for Recursion Data Structure#include <stdio.h>intfactorial(int n){// Base case: factorial of 0 is 1if(n ==0)return1;// Recursive case: multiply n with factorial of (n-1)return n *factorial(n -1);}intmain(){// case 1int number =6;printf("Number is: %d\n",6);//case 2if(number <0){printf("Error: Factorial is undefined for negative numbers.\n");return1;}int result =factorial(number);//print the outputprintf("Factorial of %d is: %d\n", number, result);return0;}

    Output

    Number is: 6
    Factorial of 6 is: 720