Factorial of any number say n is

Factorial using While Loop

So to calculate factorial of a number using while loop we need to run while loop until n!=0, each time decreasing the value of n by 1 and multiplying the number to the resultant value.

C Program for Factorial using While Loop

Output

C Program for Factorial using While Loop

Factorial using For Loop

To calculate factorial of a number using for loop, we need to run a loop from n to 1 and multiply each number into the factorial product.

C Program for Factorial using For Loop

Output

C Program for Factorial using for Loop

Factorial using Recursion

In recursion, we first need to find the base condition. In this problem the base condition is n=1. The computing part is to multiply the number with the recursive call with value n-1 i.e n * factorial(n-1).

C Program for Factorial using Recursion

Output

C Program for Factorial using recursion

Factorial using Function

To find the factorial of a number using a function, we need to create and call the function with the value of n. And the function should return the value of n’s factorial. So inside the function, we can use any method to calculate factorial of a number. It can be using:

  • For loop.
  • While loop.
  • Recursion.

We will use for loop for simplicity.

C Program for Factorial using Function

Output

C Program for Factorial using function

That’s all we need to write in C, in order to calculate factorial of a number. If the program doesn’t work for you or you have any doubt then do comment below.

Leave a Reply

Close Menu