-->

Facebook

Jasper Roberts - Blog

Monday, April 13, 2015

Recursion:

-         Recursion is the process by which a function calls itself.
-         Sometimes, the function is defined in terms of itself. For Example, factorial of a number, we say that N! = N* (N-1). Here, factorial of N is defined in terms factorial of N-1.

Advantages: 
1.      Provides easy solution for recursively defined problems. 
2.      Complex programs can be easily written with less code.


Disadvantages:
1.      Recursive code is difficult to understand and debug.
2.      Terminating condition must be required otherwise it will go in infinite loop.
3.      Execution speed decreases because of function call and return activity many times.


Example:

A C Program to find out factorial of a given number using recursion.

#include<conio.h>
#include<stdio.h>
int fact(int p);

void main()
{
            int n, ans;
            clrscr();

            printf(“Enter the number:”);
            scanf(“%d”,&n);

            ans = fact(n);

            printf(“Factorial of  a given number %d is %d”,n,ans);
            getch();
}
int fact(int p)
{
            if(p==1)
            {
            return 1;
            }
            else
            {
            return p*fact(p-1);
            }
}

OUTPUT:
Enter the number: 3
Factorial of  a given number 3 is 6