Factorial program in C

(Last Updated On: February 20, 2019)

Factorial program in C with logic and examples using loops ( for, while and do while), functions and Recursion techniques.

For example, factorial of a number 5 is 120 using below factorial formula.

Factorial Formula:

n! = n × (n − 1) × (n − 2) . . . × 2 × 1 for a number n.

Example, factorial of 5 = (5! =5*4*3*2*1=120).

NOTE:

  • factorial of 0 = 0! =1
  • No factorial for negative number

Logic:

Logic is very simple, to find a factorial of a number in C programs, just multiply the number with all its descendant numbers till 1. For example, if number is 5 then factorial = 5*4*3*2*1.

Factorial programs in C

Factorial program in C using for loop

Simple Steps

  • Prompt user to enter a number to find factorial using printf function
  • Read the number and store into a variable, say num using scanf function
  • Declare an int variable factorial which will store the result and initialize it to 1.
  • Us a for loop, and run it from i=1 to i< =num.
  • In every pass, multiply the value of variable factorial with value of i. When loop ends the factorial variable will contains the final factorial value of given number.

 

Loop explained to find factorial

 

Consider that you need to find the factorial of 5. Below is the code for every pass in the loop

C code:

 

 

Factorial program in C using while loop

Logic will be same as we used in for loop program. For simplicity, value are initialized with hard code value like num =5 and while loop has been used in the below C program.

 

 

Factorial program in C using do while loop

This C program uses do while loop but the body will be same as in while loop.

 

 

Factorial program in C using function

We will create a function e.g. getFactorial that will accept the given number as an argument, calculate the factorial using same logic as we use in loops and return the result.

We have defined the function above the main () program. If you wish to define the factorial function below the main () program then, you need to declare the function above the main() as below.

int getFactorial(int num);

C Code:

 

 

Factorial program in C using Recursion

This C code example calculate the factorial of a number using recursion technique. In brief, Recursion means, a function call itself again and again till it meets some specified condition.

Note that condition is necessary as if we don’t put the condition, the recursive call of function will go in infinite loop resulting memory over flow.

C Recursive code:

 

NOTE:
In factorial program in C language, if you find a factorial of a large number, then you need to have data type of factorial variable “unsigned long” or “unsigned long long” as its factorial value will be very larger.