In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n:

For example,

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

The factorial is normally used in Permutations and Combinations. There are multiple ways to write the factorial program in C.

Here I Listed 2 ways to write the factorial program.

Table of Contents

**Factorial Program in C using loop**

#include <stdio.h> int main() { int n, i; unsigned long long fact = 1; printf("Enter an integer: "); scanf("%d", &n); // shows error if the user enters a negative integer if (n < 0) printf("Error! Factorial of a negative number doesn't exist."); else { for (i = 1; i <= n; ++i) { fact *= i; } printf("Factorial of %d = %llu", n, fact); } return 0; }

**Factorial Program in C using Recursion**

#include <stdio.h> int fact(int n); int main() { int x, i; printf("Enter a value for x: "); scanf("%d", &x); i = fact(x); printf(" Factorial of %d is %d", x, i); return 0; } int fact(int n) { /* n=0 indicates a terminating condition */ if (n <= 0) { return (1); } else { /* function calling itself */return (n * fact(n - 1)); /*n*fact(n-1) is a recursive expression */ } }

Terminating condition(n <= 0 here;) is a must for a recursive program. Otherwise the program enters into an infinite loop.

Also See the **Palindrome program in C**

[…] Also check the Factorial Program in C […]