C

C Program to Find Factorial of a Number

The following code example demonstrates a C Program to Find Factorial of a Number. As can be seen, the program contains both recursive and non-recursive functions for computing the factorials.

Recursive Functions

Basically, a recursive function is a function that calls itself. In other words, a recursive function keeps on calling itself until a certain condition satisfies. Therefore, s recursive function must specify a terminating condition.

In contrast to a non-recursive function, a recursive function has much less number of lines of codes. So, the main feature of recursive function is its simplicity. However, a recursive function has very high time complexity in comparision to a non-recursive function for the same task.

The following program shows a recursive function that computes factorial of a number. In this case, the terminating condition reaches when the number becomes 1

#include <stdio.h>

int main()
{
    int n, nfact, rfact;
    printf("Enter a number to find the factorial of it: ");
    scanf("%d", &n);

    nfact=non_recursive_factorial(n);
    rfact=recursive_factorial(n);
    printf("\nFactorial computed in non recursive manner: %d", nfact);
    printf("\nFactorial computed in recursive manner: %d", rfact);
    return 0;
}

int non_recursive_factorial(int n)
{
    int fact=1;
    for(int i=1;i<=n;i++)
    {
        fact=fact*i;
    }
    return fact;
}

int recursive_factorial(int n)
{
    if(n<=1)
        return 1;
    else
        return n*recursive_factorial(n-1);
}

Output

Output of a C Program to Find Factorial of a Number
The output of a C Program to Find Factorial of a Number

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *