Problem: Write a Program in C to calculate an print the factorial of a number.

Factorial of any number (n) is

Factorial using While Loop

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.

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.

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).

Output

C Program for Factorial using recursion

Factorial using Function

To find the factorial of a number using a function, we need to create a function which will return the factorial of a passed number as an argument using any of the method mentioned below.

  • For loop.
  • While loop.
  • Recursion.

The function should be called from the main method and result should be returned back to the main method.

Output

C Program for Factorial using function

In this tutorial, we learned to calculate factorial of a number in C. If the program doesn’t work for you or you have any doubt then please comment below.

This Post Has One Comment

Leave a Reply