Factorial using Recursion

As a simple rule of recursion, any function can be computed using a recursive routine if :
1. The function can be expressed in its own form.
2. There exists a termination step, the point at which f(x) is known for a particular ‘x’.

Therefore to write a recursive program for the factorial of any number, we have to express the factorial function in a recursive form using the above 2 rules :
1. fact(n) = fact(n-1)*n (recursive definition of factorial).
2. if n=1, return 1 (termination step).
Using these 2 rules, the recursive program of factorial can be coded very easily as shown :

#include "stdio.h"
fact(int n)
	{ int factorial;
	  if(n==1)
	   return 1;
	  else
	   factorial=fact(n-1)*n;
	  return factorial;
	}
main()
	{ int num,factorial;
	  printf("Enter any number : ");
	  scanf("%d",&num);
	  factorial=fact(num);
	  printf("The factorial of %d is %d ",num,factorial);
	  return 0;
	}


Related Posts

Share

Filed Under: CCodes

Tags:

About the Author: Software Engineer - Search & Recommendation at Rovi

RSSComments (7)

Leave a Reply | Trackback URL

  1. John says:

    I believe I found a bug.
    0! is a special case and should evaluate to 1.

    #include “stdio.h”
    fact(int n)
    { int factorial;
    //if(n==1) breaks down for 0!
    if(n==0)
    return 1;
    else
    factorial=fact(n-1)*n;
    return factorial;
    }

    • Saurabh says:

      I believe factorial 0 has no physical significance and hence have omitted that case.
      However, I accept I should have put constraints for 0 and negative numbers.

  2. Rohan Salunkhe says:

    thanx…because of i have understand recursion program

  3. Vishnu says:

    In my point of view, factorial without using recursion is more simple method that this method

  4. SUVABRATA DAS says:

    /* Calculate factorial by using recursion */
    #include
    #include

    int fact(int n)
    {
    if(n==0)
    return 1;
    else
    return n*fact(n-1);
    }

    void main()
    {
    int num;
    clrscr();
    printf(“\n Enter a number :”);
    scanf(“%d”,&num);
    printf(“\n Factorial value=%d”,fact(num));
    getch();
    }

  5. vivek says:

    Sir please attach the algorithm too …..

Leave a Reply

*

AWSOM Powered