Recursion


Recursion
Ø  In C, it is possible for the functions to call themselves. A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’,
Ø  A function calls itself is called as a Recursion.
Ø  Generally we write these recursive function with if . . else statements .a function calls recursively until the given if condition is satisfied.

Ø   When writing recursive functions, you must have an If stmt some where in the recursive function to force the function to return with out recursive call being executed.
Ø  If you do not do this and you call the function, you will fall in an indefinite loop, and will never return from the called function
Ø   


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

     int factorial(int);
     main( )
    {
int n,k;
printf(“enter any number\n”);
scanf(“%d”,&n);
k=factorial(n);
printf(“factorial of  %d is %d”,n,k);
getch( );
    }
int factorial(int x)
{
int fact;
if(x==0||x==1)
     return(1);
else
     return (x*factorial(x-1));

}
 
Ø  In case the value of n is 4, main() would call factorial() with 4 as its actual argument, and factorial() will send back the computed value. But before sending the computed value, factorial() calls factorial() and waits for a value to be returned.
 

            factorial(4) returns 4*factorial(3)
factorial(3) returns 3*factorial(2)
factorial(2) returns 2*factorial(1)
factorial(1) returns 1


No comments:

Post a Comment