Friday, 30 March 2012

Recursion


Recursion

è      When any called function in turn calls  another function a process of chaining occurs.
è      When function calls itself the process is known as recursion.Recursion is a special case of this process , where a function calls itself.
Ex,
          void main()
                   {
                             printf(“\n This is recursive main()”);
                             main();
                   }
Here the main() calls itself and the message written in printf() will display. Execution is terminated abruptly ; otherwise the execution will continue indefinitely.

The calculation of factorial of given number can be easily find out using recursion. Factorial of a number n is expressed as a series of repetitive multiplication as shown below.
Factorial of 5 =5*4*3*2*1
                    = 120
Ex
#include<stdio.h>
#include<conio.h>

int fact(int);
void main()
 {
    int n,f;
    clrscr();
    printf("\n Enter any number : ");
    scanf("%d",&n);
    f=fact(n);
    printf("\n Factorial of %d = %d",n,f);
    getch();
 }
int fact(int n)
 {
    if(n==1)
      {
          return(1);
      }
    else
      {
          return(n*fact(n-1));
      }
 }
The execution of recursion is as follw:
Suppose n=5 then,
First checks    if(n==1)  since the value of n in not 1 , the statement
return(n*fact(n-1)); will execute as :
 

return(5*fact(4));     5*24  =120
return(4*fact(3));     4*6   =24
return(3*fact(2));     3*2   =6
return(2*fact(1));     2*1   =2

          When n=1 then returns 1 to the last call of function.

Posted By : Ruchita Pandya

No comments:

Post a Comment