Detailed Explanation of Factorial Program in C

In C language, the factorial is the result of multiplying all positive integers from large to small. The factorial of n is represented as n!. For example:

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

  2. 3! = 3 * 2 * 1 = 6

Here, 5! is read as “5 factorial”, also known as “5 factorial” or “5 bang”.

Factorials are often used in combinations and permutations (mathematics).

There are many ways to write a factorial program in C. Let’s look at two ways to write a factorial program:

  • Writing a factorial program using loops

  • Writing a factorial program using recursion


👇 Click to receive 👇
👉 C Language Knowledge Material Collection


Writing a Factorial Program Using Loops

Let’s see how to write a factorial program using loops.

#include <stdio.h>
int main() {  int i, fact = 1, number;  printf("Please enter a number:");  scanf("%d", &number);
  for (i = 1; i <= number; i++) {      fact = fact * i;  }
  printf("%d factorial is: %d", number, fact);  return 0;}

Output:

Please enter a number: 5 factorial is: 120

Writing a Factorial Program Using Recursion in C

Let’s see how to write a factorial program using recursion in C.

#include <stdio.h>
long factorial(int n) {  if (n == 0)      return 1;  else      return (n * factorial(n - 1));}
int main() {  int number;  long fact;
  printf("Please enter a number:");  scanf("%d", &number);
  fact = factorial(number);  printf("%d factorial is: %ld\n", number, fact);
  return 0;}

Output:

Please enter a number: 6 factorial is: 720

Detailed Explanation of Factorial Program in C


Popular Recommendations
  • C Language Tutorial – Detailed Explanation of Palindrome Program in C

  • C Language Algorithm – “Missing First Positive Number” Algorithm Problem

  • C++ Tutorial – Basic Output in C++ Language

Leave a Comment