When you multiply a positive integer by all the integers smaller than that positive integer, you get its factorial. This article will explain what is factorial and how to write a factorial program in C with examples.

**For example**, factorial of 3 is **3! = 1*2*3 = 6** and factorial of 6 is **6! = 6 * 5 * 4 * 3 * 2 * 1** which equals to **720**.

By default, the factorial of 0 is 1, and Factorial of a negative number is not defined.

In mathematics, a factorial is denoted by “**!**“. Therefore, the factorial of **n** is given by the formula

**n! = n x (n-1) x (n-2) x (n-3) … x1**.

Factorial can also be calculated using Euler’s gamma function which is

**n! = γ(n+1) = \(∫_0^∞\) x ^{n} e^{-x} dx**

Write a program to find the factorial of a positive number. If number is negative print the message otherwise find the factorial of the number.

There are several ways to find factorial of a number in C. Let’s look at five different approaches

to program this function:

- Factorial Program in C using For Loop
- Factorial Program in C using While Loop
- Factorial Program in C using Recursion
- Factorial Program in C using Ternary Operator
- Factorial Numbers in a Given Range
- Optimised Solution for Factorial of Range of Numbers

In this method, we run a loop for N times and multiply all the N positive numbers.

Here is source code of the C program to print the factorial of a given number using for loop (iterative solution). The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C program to find the factorial of a given number using for loop. */ #include <stdio.h> void main() { // fact to store factorial of number N int fact = 1, n; // Take input printf("Enter the number: \n"); scanf("%d", &n); // Check validity of N if (n <= 0) fact = 1; // Loop N times and multiply all positive numbers else { for (int i = 1; i <= n; i++) { fact = fact * i; } } // Print the fact. printf("Factorial of %d = %5d\n", n, fact); }

1. Take a number and store it in ‘**n**’.

2. Check whether it is a valid number or not.

3. If not a valid number, print the message.

4. Else, run a for loop from **1 to N**.

5. Take a variable ‘**fact**’ and store all the multiplication of **N** numbers in it.

6. Print the factorial value.

**Example:**

Take N=6, check whether N is less than 0. If it is less than zero, print message. Now we run a for loop from N=1 to N=6 and multiply all the numbers. Store the multiplication of numbers in a variable and print the answer.

**Time Complexity: O(N)**

Since we are running for loop for N times, it’s time complexity is O(N).

**Space Complexity: O(1)**

Since we are not using constant space for computation, it’s space complexity is O(1).

Here is the runtime output of a C program to find the factorial of a number when the number entered by the user is “6”.

Enter the number: 6 Factorial of 6 = 720

In this method we run a loop for N times and multiply all the N positive numbers.

Here is source code of the C program to print the factorial of a given number using while loop (iterative solution). The C program is successfully compiled and run on a Linux system. The program output is also shown below.

// c program to calculate factorial of a number using while loop #include <stdio.h> int main() { int num, i = 1; unsigned long long int factorial_of_num = 1; printf("Enter the number whose factorial you want to calculate: "); scanf("%d", &num); while (i <= num) { factorial_of_num *= i; i++; } printf("Factorial of %d is %llu ", num, factorial_of_num); return 0; }

**Time Complexity: O(N)**

Since we are running for loop for N times,it’s time complexity is O(N).

**Space Complexity: O(1)**

Since we are not using constant space for computation, it’s space complexity is O(1).

In this case, we enter the number “7” to determine the factorial.

Enter the number whose factorial you want to calculate: 7 Factorial of 7 is: 5040

It is a recursive problem and the solution of factorial of N is given by expression

**fact(n) = n*fact(n-1)**

In above expression, we get solution of **(n-1)!** by recursive function and when we multiply it with **n**, we get result of **n!**.

Here is source code of the C program to print the factorial of a given number using recursive function. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C program to find the factorial of a given number using recursion */ #include <stdio.h> int factorial(int n) { // Base case for factorial function if (n == 0 || n == 1) { return 1; } else { return(n * factorial(n - 1)); } } int main() { // The number to calc n! int n; // variable to store ans int ans; printf("Enter a number to find it's Factorial: "); scanf("%d", &n); if (n < 0) { printf("Factorial of negative number not possible\n"); } else { // Calling factorial method ans = factorial(n); printf("The Factorial of %d is %d.\n", n, ans); } return 0; }

1. Take a number and store it in ‘n’.

2. Check whether it is a valid number or not.

3. If not a valid number, print the message.

4. Else, call recursive function.

5. Call same function for ‘n-1’ to get it’s factorial and multiply it with ‘n’ to get factorial of desired number.

6. Include the base case to stop the recursion.

7. Finally, print the answer.

**Example:**

Take N=10, check N!=0 and N!=1, so it calls equation 10*factorial(9).

Now again N=9, since N!=0 || N!=1, so it calls equation 9*factorial(8).

This process takes on until we call 2*factorial(1). factorial(1) returns 1, therefore multiplication of

all the numbers gets computed and displays the value i.e 3628800.

**Time Complexity: O(N)**

Since we are calling function for N times(N,N-1,N-2….3,2,1), time complexity is O(N).

**Space Complexity: O(N)**

In the context of recursion, a memory tree is created during execution, taking into account that

the space complexity of the tree is O(N).

Here is the runtime output of a C program to find the factorial of a number when the number entered by the user is “10”.

Enter a number to find it's Factorial: 10 The Factorial of 10 is 3628800

In this method we use ternary operator to call recursive function.

Here is source code of the C program to print the factorial of a given number using ternary operator to call recursive function. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C program to find the factorial of a given number using ternary operator */ #include <stdio.h> int factorial(int n) { // Using ternary operators return ((n==0||n==1)?1:n*factorial(n-1)); } int main() { // The number to calc n! int n; // variable to store ans int ans; printf("Enter a number to find it's Factorial: "); scanf("%d", &n); if (n < 0) { printf("Factorial of negative number not possible\n"); } else { // Calling factorial method ans = factorial(n); printf("The Factorial of %d is %d.\n", n, ans); } return 0; }

**Working of ternary operators (?:)**

(condition) **?** (output if condition is true) **:** (output if condition is false)

We will write the base condition before ‘**?**’. If condition turns out to be true we return the base case else we will call recursive function.

**Example:**

Take N=6, check **N!=0 || N!=1**, so it calls equation 6*factorial(5).

Now again N=5, since **N!=0 || N!=1**, so it calls equation 5*factorial(4).

This process takes on until we call **2*factorial(1). factorial(1)** returns 1, therefore multiplication of

all the numbers gets computed and displays value i.e. 720.

**Time Complexity: O(N)**

Since we are calling function for N times(N,N-1,N-2….3,2,1), time complexity is O(N).

**Space Complexity: O(N)**

Recursion forms a tree in the memory during execution, keeping that factor into consideration

space complexity is O(N).

To find the factorial of a number, we enter “7” in this case.

Enter a number to find it's Factorial: 6 The Factorial of 6 is 720

In this method, we get start and end value of range. Print the factorials for all the numbers in this range.

Here is source code of the C program to print the factorial numbers in a given range. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C program to find the factorial factorial numbers in a given range. */ #include<stdio.h> int main() { long fact=1; int start,end; printf("Enter the starting value of range: "); scanf("%d",&start); printf("Enter the ending value of range: "); scanf("%d",&end); printf("Factorial series of the given range is: "); for(int n=start;n<=end;n++) { // Calculating factorial for each number of range fact=1; for(int x=1;x<=n;x++) { fact=fact*x; } // Printing the output printf("%ld ",fact); } return 0; }

1. Take the start value and end value of range as input.

2. Loop for each value in the range.

3. Calculate the factorial of each value of the given range by iterating again for ‘N’ times.

**Example:**

Take start of range as **4** and end of range is **8**.

Loop From **N=4 to N=8**

Take N=4, Now we run a for loop from **N=1 to N=4** and multiply all the numbers. Store the multiplication of numbers in a variable and print the answer. Similarly, we do this till N=8 and print all the factorial value i.e **24 120 720 5040 40320**.

**Time Complexity: O(N ^{2})**

Since we are applying two nested loops, time complexity will be O(N

^{2}).

**Space Complexity: O(1)**

We are using constant space for computation, therefore space complexity will be O(1).

To find the factorial of a number in a given range, enter the starting value as “4” and ending value as “8” as input.

Enter the starting value of range: 4 Enter the ending value of range: 8 Factorial series of the given range is: 24 120 720 5040 40320

**Scope Of Optimization:** We are iterating to each value of given range and computing the factorial of each number by iterating from 1 to that particular value.

If we store the multiplication of numbers before the start number of given range, we can compute the factorial of given range by multiplying the particular number.

Here is source code of the C program to print the factorial numbers in a given range using optimised approach. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C program to find the factorial factorial numbers in a given range. */ #include<stdio.h> int main() { long fact=1; int start,end; printf("Enter the starting value of range "); scanf("%d",&start); printf("Enter the ending value of range "); scanf("%d",&end); printf("Factorial series of the given range is: "); int a=1; // Preconpute multiplication of numbers smaller than start for(int i=1;i<start;i++) { a=a*i; } // Iterate from start to end for(int n=start;n<=end;n++) { // Compute factorial fact=a*n; // Update the precomputed value a=a*n; printf("%ld ",fact); } return 0; }

1. Take the start value and end value of range as input.

2. Precompute the multiplication of all the numbers smaller than start value and store it in ‘**a**’.

3. Iterate from start to end.

4. Multiply each number from precomputed value and print the answer.

5. After that update the precalculated value by recently calculated value.

**Example:**

Take start of range as **4** and end of range is **8**.

Now we run a for loop from **N=1** to **N=3** and multiply all the numbers. Store the multiplication of numbers in a variable ‘**a**’.

Loop From N=4 to N=8

Take N=4, we multiply ‘**a**’ with N and print the answer. Now we update ‘**a**’ with **a*N**.

Take N=5, we multiply ‘**a**’ with N and print the ans. Now we update ‘**a**’ with **a*N**. Similarly, we do this till N=8 and print all the factorial value i.e **24 120 720 5040 40320**.

**Time Complexity: O(N)**

We are implementing two loops but they are not nested. Therefore time complexity is O(N).

**Space Complexity: O(1)**

We are using constant space for computation therefore space complexity is O(1).

To find the factorial of a number in a given range, enter the starting value as “4” and ending value as “8” as input.

Enter the starting value of range: 4 Enter the ending value of range: 8 Factorial series of the given range is: 24 120 720 5040 40320

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

**Next Steps:**

- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

**Related Posts:**

- Practice Computer Science MCQs
- Practice BCA MCQs
- Buy C Books
- Watch Advanced C Programming Videos
- Buy Computer Science Books