Saturday, April 23, 2011

Calculating Factorial Using Recursion in C

Factorial: its a mathematical function defined as 4!=4x3x2x1=120. Yes just like that. It will multiply all numbers before the given numbers till 1(Worst definition ever).


Method: recursive method is pretty easy too. because n!=n*(n-1)! and we know that 1!=1.
so Terminating condition: at n==1 result =1.
Recursive definition : n!=n*(n-1)!
Code in C: 
#include<stdio.h>
int factorial(int x)
{
    if(x==1)
    {
        return(1);
    }
    else
    {
        return(x*factorial(x-1));
    }
}
int main()
{
    int n;
    printf("\n Enter the number to calculate its factorial=");
    scanf("%d",&n);
    printf("\n Factorial of number =%d",factorial(n));
}

No comments:

Post a Comment