5 ways to find factorial of number in c programming

factorial of a number in c

Factorial is used in many areas of mathematics but mainly used in permutation and combination. Factorial is the product of the all positive number from 1 to n (user entered number). In simple word, we can say that factorial of n would be 1*2*3*…..*n.

Note: There is no factorial exist for the negative number and value of !0 is 1.




Factorial of positive number would be:

!n  = n * !(n-1)

For example,

!5 =  5*4*3*2*1*!0  =  120.

Some factorials of numbers

nn!
01
11
22
36
424
5120
6720
75040
840320
9362880
103628800

 

Here I am describing the few methods to calculate the factorial of a positive number in C. I hope you are familiar with while and for loop in c.

 Factorial of a number in c using the for loop

The below program takes a positive integer number from the user and computes its factorial using the for loop.

OutPut

When the user Enters the negative number.

factorial

When the user enters the positive number.

factorial

Factorial of a number using the recursive method.

 

A function is called recursive, if it is called by itself. You can see this article, Recursion in C. Before writing the code I want to show here a flow diagram which to describe the flow of the code.

factorial in c

 

recursive function in c

 

Working of the above code,

Here n = 3

fact(3) = 3 * fact(2)
fact(2) = 2* fact(1)
fact(1) = 1 *fact(0);

When n=0, condition becomes true and recursion stops and control returns to factorial(1). Now reverse process occurs and function will return a value to the previous function calls.

Note: There should be a termination point in a recursive function.

recursive function

 

So the final result will be:

fact(3) = 3*2*1 = 6

Factorial of a number in c using the while loop

 




Calculate the factorial using the look-up table

If you need the factorial of the small number then look up table is the best option because it is fast as compared to iteration and recursion method.
In below program, I am creating a look-up table which contains the factorial of-of 0 to 10;

Calculate the factorial using a function

 




Leave a Reply