January 22, 2013

Recursive Function


recursion abstract of desktop

This function is that function which calls itself again and again until some base criteria is fulfilled. It means it is that prototype function in which its name appears as a statement at least once. 

      int fun(int x)
        {
           Statement1;
           Statement2;
           Statement3;
           fun (x-1);
           statement4;
         }

It starts from initial given conditions and it gives output, this output is used as input in the next step and this method will continue till terminal condition is encountered. This function will create self loop which works like for loop and its format:
        void main()
        {
            int t,n,f;
            ……………. ;
            ……………. ;
           scanf(“%d”,&n);
           t= fun (n);
           printf(“\n %d”,f);
          }

/*Program to find the factorial of a number using recursion */

#include<stdio.h>
#include<conio.h>
long factorial(int f);
main()
{
     int n;
     long f;
     printf("\n enter any value of n whose factorial is to find");
     scanf("%d",&n);
     f=factorial(n);
     printf("\n factorial of %d is %ld",n,f);
     getch();
     }
     long factorial(int f)
     {
          long fact;
          if(f==0 || f==1)
          return fact=1;
          else
          fact=f*factorial(f-1);
          return fact;
          }
output of factorial of a number using recursion in C language

/*Program to print fibonacci series using recursion */

#include<stdio.h>
#include<conio.h>
int fab(int n);
void main()
{
     int n,f,i;
     printf("\n enter the limit of the fibonacci series");
     scanf("%d",&n);
     for(i=1;i<=n;i++)
     {
                      f=fab(i);
                      printf("%d ",f);
                      }
     getch();
     }
int fab(int n)
{
    int x;
    if(n==1)
    return x=0;
    else if(n==2)
    return x=1;
    else if(n!=1 && n!=2)
    x=fab(n-2)+fab(n-1);
    return x;
}
output of fibonacci series using recursion in C language
     


No comments:

Post a Comment