Monday, 2 October 2017

Recursive Function Examples Using C (Factorial, Fibonacci Number, Combination, Permutation and Tower Of Hanoi).

A recursive function is a function which either calls itself or is in a potential cycle of function calls. Here some simple examples of recursive functions are given like factorial of a number, Fibonacci number series, combination, permutation & tower of Hanoi.

Source code:
#include <stdio.h>
#include <conio.h>

// n! = n*(n-1)! & 0! = 1
double fact(unsigned int number)
{
     if (number == 0)
           return(1.00);
     else
           return(number*fact(number - 1));
}

//fib(n) = fib(n-1)+fib(n-2) for n>2 &  fib(0) =0 ,fib(1) =1;
unsigned int fib_num(unsigned int number)
{
     if (number>=2)
           return(fib_num(number - 1) + fib_num(number - 2));
     else
     {
           if (number)
                return(1);
           else
                return(0);
     }
}

//nCr = (n-1)C(r-1)+(n-1)C(r-1) if r<=n else 0; & nC0=1;
unsigned int nCr(unsigned int _tot,unsigned int _comb)
{
     if (!_comb)
     {
           return 1;
     }
     else if (_comb <= _tot)
     {
           return (nCr(_tot - 1, _comb - 1) + nCr(_tot - 1, _comb));
     }
     else
     {
           return 0;
     }
}

//nPr = (n-r+1)*nP(r-1) if r<=n else 0; & nP0=1;
int nPr(unsigned int _totunsigned int _perm)
{
     if (!_perm)
     {
           return 1;
     }
     else if (_perm <= _tot)
     {
           (_tot - _perm + 1) * nPr(_tot_perm - 1);
     }
     else
     {
           return 0;
     }
     return(fact(_perm)*nCr(_tot_perm));
}

// Solve for first (n-1) disks, then for (n-2),(n-3)...
void tower_of_hanoi(unsigned int numberchar *Bchar *Achar *E)
{
     if (number)
     {
           tower_of_hanoi(number - 1, BEA);
           printf("move disks from tower%s to tower%s"BE);
           printf("\n");
           tower_of_hanoi(number - 1, ABE);
     }
     return;
}

int main()
{
     printf("**Recursive Function Examples**\n");
     printf("\n_______________________________________________________________\n");
     printf("Factorial of 7 = %f\n", fact(7));
     printf("\n_______________________________________________________________\n");
     printf("Fibonacci numbers series up 12 numbers\n");
     for (size_t i = 0; i < 12; i++)
     {
           printf("  %d", fib_num(i));
     }
     printf("\n_______________________________________________________________\n");
     printf("\n**combination & permutation**");
     printf("\n 23 C 3 = %d", nCr(23, 3));
     printf("\n 23 P 3 = %d", nPr(23, 3));
     printf("\n_______________________________________________________________\n");
     printf("\nSolution of tower of hanoi for 4 disks\n");
     tower_of_hanoi(4, "1""2""3");
     printf("\n_______________________________________________________________\n");
     getchar();
     return 0;
}

Output: