Ads block

Banner 728x90px

Factorial

We know that the factorial of a positive integer n can be found out by multiplying all integers from 1 to n.
n! = 1 * 2 * 3 *...........*(n-1) * n

This is the iterative definition of factorial, and we can easily write an iterative function for it using a loop. Now we will try to find out the solution of this factorial problem recursively.

We know that-         4! = 4 * 3 * 2 * 1
We can write it as-  4! = 4 * 3!   (since 3! = 3 *2 *1)
Similarly                   3! = 3 * 2!
                                  2! = 2 * 1!
                             1! = 1 * 0!

So in general we can say that factorial of a positive integer n is the product of n and factorial of (n-1).
n! = n * (n-1)!


Now problem of finding out factorial of (n-1) is similar to that of finding out factorial of n, but it is smaller in size. So we have defined the solution of factorial problem in terms of itself. We know that the factorial of 0 is 1. This can act as the terminating candition or the base case.

Now we will write a program, which finds out the factorial using a recursive function.

#include<stdio.h>
int fact(int n);
main()
 {
    int num;

    printf("Enter a number: \n");
    scanf("%d", &num);
    if(num<0)
         printf("No factorial for negative number\n");
    else
         printf("Factorial of %d is %d\n", num, fact(num));
 }
int fact(int n)
 {
    if(n == 0)
         return(1);
    return(n * fact(n-1));
 }