Factorial Example in C Programming Complete Example with algorithm and code examples

Algorithm


Basic factorial algorithm - 

Defined,

0! = 1

 

n! = n*(n-1)*(n-2)*(n-3)...

 

That means = 3! = 3 * (3-1) * (3-2).

 

  1. Take the number
  2. Set factorial = 1
  3. Loop throw the number
    1. Inside loop, update the factorial = factorial * incremented no
  4. Finally, get the factorial result from factorial

Code Examples

#1 Code Example with C Programming

Code - C Programming

#include <stdio.h>
 
int main()
{
  int i, num, fact = 1;
 
  printf("Enter Number to Calculate Factorial: \n");
  scanf("%d", &num);
  
  for (i = 1; i <= num; i++){
      fact = fact * i;
  }
    
  printf("Factorial of %d = %d\n", num, fact);
 
  return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
Enter Number to Calculate Factorial: 5

Output

x
+
cmd
Factorial of 5 = 120

Demonstration


Explanation for 5!

fact = 1

// Start Loop from 1 to 5

fact = fact * 1 = 1  * 1 = 1     // i = 1
fact = fact * 2 = 1  * 2 = 2     // i = 2
fact = fact * 3 = 2  * 3 = 6     // i = 3
fact = fact * 4 = 6  * 4 = 24    // i = 4
fact = fact * 5 = 24 * 5 = 120   // i = 5