View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
c tutorial

Explore C Tutorials: From Begi…

  • 132 Lessons
  • 22 Hours

C Program for Factorial

Updated on 05/02/20255,237 Views

A factorial, n!, is the product of every positive integer less than or equal to a given number n. For example, if n=5, the factorial is calculated as:

5! = 5 × 4 × 3 × 2 × 1 = 120

Although factorial is not definited for negative numbers, the factorial of 0 by definition is 1.

Calculating the factorial is a common programming problem. It helps practice core concepts like loops, recursion, and mathematical operations, and is useful in various real-world applications.

In this tutorial, you’ll learn different ways to calculate factorial using C programs, with simple examples for easy understanding.

Improve your C programming skills with our Software Development courses — take the next step in your learning journey!

Steps to Calculate the Factorial

Let’s calculate the factorial of 5:

Step 1: Start with a result of 1 (because the factorial of any number starts from 1).

Result = 1

Step 2: Multiply the result by each number from 1 to n (in this case, n = 5).

Multiply result by 1: Result = 1 × 1 = 1

Multiply result by 2: Result = 1 × 2 = 2

Multiply result by 3: Result = 2 × 3 = 6

Multiply result by 4: Result = 6 × 4 = 24

Multiply result by 5: Result = 24 × 5 = 120

Step 3: After all iterations, the result is 120, which is the factorial of 5.

C Program for Calculating Factorial

Here’s how you can calculate factorial using C program:

#include <stdio.h>
int main() {
int n = 5; // The number whose factorial we want to calculate
int result = 1; // Start with result 1
// Loop through numbers from 1 to n
for (int i = 1; i <= n; i++) {
result *= i; // Multiply the result by the current number
}
// Print the result (factorial of 5)
printf("The factorial of %d is %d\n", n, result);
return 0;
}

Output:

The factorial of 5 is 120

Also Read: Top 25+ C Programming Projects for Beginners and Professionals

Now, let's dive into different implementations of the C program for factorial.

Various Methods to Calculate Factorial Using C Program

While the basic concept of calculating the factorial stays the same, there are multiple ways to implement it in C. Let’s explore each of them in more detail:

C Program for Factorial Using For Loop

A for loop in C is used to repeat a block of code a specific number of times. It is typically used when the number of iterations is known beforehand, such as in calculating a factorial by looping through each number from 1 to n.

Here is a simple C program to find the factorial of a number using a for loop:

#include <stdio.h>
int main() {
int n = 5; // The number whose factorial we want to calculate
int result = 1; // Initialize result to 1
// Loop to calculate factorial
for (int i = 1; i <= n; i++) {
result *= i; // Multiply result by the current value of i
}
// Print the factorial
printf("The factorial of %d is %d\n", n, result);
return 0;
}

Explanation:

1. n = 5: We're calculating the factorial of 5.

2. result = 1: We start with 1 because multiplying by 1 doesn’t change the result.

3. For loop: It runs from 1 to 5, multiplying result by each number from 1 to 5.

  • First, result = 1 * 1 = 1
  • Then, result = 1 * 2 = 2
  • Next, result = 2 * 3 = 6
  • Then, result = 6 * 4 = 24
  • Finally, result = 24 * 5 = 120

Output:

The factorial of 5 is 120

Also Read: String Functions in C

C Program for Factorial Using While Loop

This method uses a while loop to calculate the factorial of a number by repeatedly multiplying the result until the condition is met. It is useful when the number of iterations is not fixed, but determined by the user input.

Here's a simple C program to calculate the factorial of a number using a while loop:

#include <stdio.h>
int main() {
int n = 5; // The number whose factorial we want to calculate
int result = 1; // Initialize result to 1
int i = 1; // Initialize the loop counter
// Using while loop to calculate factorial
while (i <= n) {
result *= i; // Multiply result by current value of i
i++; // Increment i
}
// Print the factorial
printf("The factorial of %d is %d\n", n, result);
return 0;
}

Explanation:

1. n = 5: We're calculating the factorial of 5.

2. result = 1: Start with 1 because multiplying by 1 doesn't change the result.

3. i = 1: Initialize the counter for the loop.

4. While loop: The loop runs as long as i is less than or equal to n. In each iteration, it multiplies the result by i and then increments i.

  • First, result = 1 * 1 = 1
  • Then, result = 1 * 2 = 2
  • Next, result = 2 * 3 = 6
  • Then, result = 6 * 4 = 24
  • Finally, result = 24 * 5 = 120

Output:

The factorial of 5 is 120

Also Read: Command Line Arguments in C Explained

C Program for Factorial Using Recursion

In this approach, the factorial is calculated using a recursive function, where the function calls itself with a reduced value of the number until a base condition is met. It’s a clean and efficient method, although it can be less memory efficient for large numbers.

In recursion, the base case stops the function from calling itself indefinitely.

  • For factorial, the base case is when n == 0 or n == 1, where the result is 1.
  • The recursive case calls the function with a smaller value (factorial(n - 1)) and multiplies it by n, continuing until the base case is reached.

However, stack overflow can occur if n is too large, as each recursive call adds a new stack frame. To avoid overflow, use long long for larger numbers, but values over 20! can still cause overflow.

For even larger values, consider using arbitrary-precision libraries like GMP to handle factorials beyond standard integer limits.

Here’s a simple C program to calculate the factorial of a number using recursion:

#include <stdio.h>
// Function to calculate factorial using recursion
int factorial(int n) {
// Base case: if n is 0 or 1, return 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive case: n * factorial of (n-1)
return n * factorial(n - 1);
}
}
int main() {
int n = 5; // The number whose factorial we want to calculate
// Call the factorial function and print the result
printf("The factorial of %d is %d\n", n, factorial(n));
return 0;
}

Explanation:

1. factorial function: This function calculates the factorial of a number using recursion.

2. Base case: If n is 0 or 1, it returns 1 because the factorial of both 0 and 1 is 1.

3. Recursive case: If n is greater than 1, it calls the factorial function with n-1 and multiplies the result by n.

4. Recursion: The function repeatedly calls itself until it reaches the base case, where it stops and begins returning values.

For example:

  • factorial(5) returns 5 * factorial(4)
  • factorial(4) returns 4 * factorial(3)
  • This continues until factorial(1) returns 1.

Output:

The factorial of 5 is 120

Also Read: What Are Storage Classes in C?

C Program for Factorial Using Ternary Operator

This method uses the ternary operator for a compact and conditional calculation of factorial. It’s a shorthand for an if-else statement, making the program shorter but still functional in calculating the factorial.

Here's a C program to calculate the factorial of a number using the ternary operator:

#include <stdio.h>
// Function to calculate factorial using ternary operator
int factorial(int n) {
return (n == 0 || n == 1) ? 1 : n * factorial(n - 1); // Ternary operator
}
int main() {
int n = 5; // The number whose factorial we want to calculate
// Call the factorial function and print the result
printf("The factorial of %d is %d\n", n, factorial(n));
return 0;
}

Explanation:

Ternary Operator: The ternary operator ? : is used to simplify the logic in the function. It has the format: condition ? expression_if_true : expression_if_false;

  • If n == 0 || n == 1, the factorial is 1 (the base case).
  • Otherwise, it recursively calls factorial(n - 1) and multiplies it by n (the recursive case).

Example - factorial(5): The ternary operator checks if n == 0 or n == 1. If not, it recursively calls the factorial function, and the result is multiplied by n.

Output:

The factorial of 5 is 120

Also Read: Difference Between C and Java: Which One Should You Learn?

C Program for Factorial Using tgamma() Method

The tgamma() function, found in the math.h library, calculates the Gamma function, which is related to the factorial function: n! = Gamma(n + 1).

While the Gamma function is defined for real and complex numbers, factorials are defined only for non-negative integers. Calling tgamma(n + 1) effectively computes n!. For example, tgamma(6) returns 5!.

The function returns a double, which can lose precision for large values.

Factorials beyond 170! will overflow, even with double. Always include math.h to use tgamma(). Additionally, tgamma() returns NaN for invalid inputs, such as negative numbers or zero.

In C, the tgamma() function from the math.h library can be used to compute the factorial of a number. The tgamma() function returns the value of the Gamma function, which is related to the factorial by the formula:

n! = Gamma(n + 1)

Here’s a C program to calculate the factorial of a number using the tgamma() method:

#include <stdio.h>
#include <math.h> // Include the math.h library for tgamma()
int main() {
int n = 5; // The number whose factorial we want to calculate
// Use the tgamma function to calculate factorial
// tgamma(n + 1) gives the factorial of n
printf("The factorial of %d is %.0f\n", n, tgamma(n + 1));
return 0;
}

Explanation:

1. tgamma(n + 1): The tgamma() function calculates the Gamma function of n + 1. Since Gamma(n + 1) is equivalent to n!, it directly returns the factorial of n.

2. The result of the tgamma() function is a floating-point number, so we use %.0f to print it as an integer without decimals.

3. Example: For n = 5, the program calculates tgamma(6), which is equivalent to 5!.

Output:

The factorial of 5 is 120

Also Read: What is Array in C? With Examples

C Program for Factorial Using Function

In this approach, a function is used to calculate the factorial, making the program more modular and reusable. The function can be called with any number, allowing for cleaner code and easier maintenance.

Here’s a simple C program to calculate the factorial of a number using a function:

#include <stdio.h>
// Function to calculate factorial
int factorial(int n) {
int result = 1; // Initialize result to 1
for (int i = 1; i <= n; i++) {
result *= i; // Multiply result by the current number
}
return result; // Return the factorial
}
int main() {
int n = 5; // The number whose factorial we want to calculate
// Call the factorial function and print the result
printf("The factorial of %d is %d\n", n, factorial(n));
return 0;
}

Explanation:

1. factorial function: This function takes an integer n and calculates the factorial using a for loop.It multiplies the result by each number from 1 to n to compute the factorial. Finally, it returns the result.

2. main function: We define the number n = 5, which is the number whose factorial we want to calculate. The factorial() function is called with n as the argument, and the result is printed.

Output:

The factorial of 5 is 120

This program uses a function to calculate the factorial of a given number, making it reusable for different inputs.

Also Read: Data Types in C and C++ Explained for Beginners

C Program for Factorial Using Pointers

This method involves using pointers to pass the result of the factorial calculation to the function. It helps in understanding memory management and direct memory access while calculating the factorial.

Pointers in C store the memory address of a variable, allowing indirect modification. In this program, a pointer is used to update the result directly in the main function.

Dereferencing the pointer with * modifies the value at the address. The factorial function uses the pointer to update the result by multiplying it with i.

Pointers enable passing by reference, modifying the original variable. The & operator passes the address of result. For large factorials, use long long to prevent overflow in standard data types.

Here is a simple C program to calculate the factorial of a number using pointers:

#include <stdio.h>
// Function to calculate factorial using pointers
void factorial(int n, int *result) {
*result = 1; // Initialize result to 1
for (int i = 1; i <= n; i++) {
*result *= i; // Multiply result by current number
}
}
int main() {
int n = 5; // The number whose factorial we want to calculate
int result; // Variable to store the factorial
// Call the factorial function, passing the address of result
factorial(n, &result);
// Print the result (factorial)
printf("The factorial of %d is %d\n", n, result);
return 0;
}

Explanation:

1. factorial function: This function takes two arguments: an integer n (the number whose factorial we want to calculate) and a pointer *result (where the calculated factorial will be stored).

Inside the function, the pointer *result is used to update the factorial value. The factorial is calculated using a for loop, and the pointer stores the result.

2. main function: We define the number n = 5, which is the number whose factorial we want to calculate. The factorial() function is called, and we pass the address of result (using &result) so the function can modify its value. The result is then printed.

Output:

The factorial of 5 is 120

This version of the program uses pointers to store the factorial result, making it more flexible and demonstrating how pointers work in C.

Also Read: Top 3 Open Source Projects for C [For Beginners To Try]

C Program to Find Factorial Series

This program calculates the factorial series for a number, meaning you can find the factorial of each number from 0 to a given number n. The factorial of a number n is the product of all positive integers from 1 to n.

For example:

  • 0! = 1
  • 1! = 1
  • 2! = 2 × 1 = 2
  • 3! = 3 × 2 × 1 = 6
  • 4! = 4 × 3 × 2 × 1 = 24
  • and so on...

Here's how the program works:

#include <stdio.h>
// Function to calculate the factorial of a number
long long factorial(int n) {
long long fact = 1; // Start with fact = 1
for (int i = 2; i <= n; i++) { // Loop from 2 to n
fact *= i; // Multiply fact by i at each step
}
return fact; // Return the calculated factorial
}
int main() {
int num;
// Ask the user to input the number of terms in the series
printf("Enter the number of terms in the series: ");
scanf("%d", &num);
printf("The factorial series up to %d is:\n", num);
// Loop from 0 to num and calculate the factorial for each number
for (int i = 0; i <= num; i++) {
// Call the factorial function and print the result
printf("Factorial of %d = %lld\n", i, factorial(i));
}
return 0; // End of the program
}

Explanation:

1. Factorial Function: This function calculates the factorial of a given number n. It initializes a variable fact to 1, then uses a for loop to multiply fact by every number from 2 to n.

For example, if n is 4, the loop will multiply fact like this:

fact = 1 * 2 = 2,

fact = 2 * 3 = 6,

fact = 6 * 4 = 24.

So, the factorial of 4 is 24.

2. Main Function: The main part of the program asks the user to enter a number (how many terms of the factorial series they want). It then prints the factorial of each number from 0 to the input number.

For example, if the user inputs 4, the program will print:

Factorial of 0 = 1

Factorial of 1 = 1

Factorial of 2 = 2

Factorial of 3 = 6

Factorial of 4 = 24

3. Handling Large Numbers: Since factorials grow very quickly, the program uses long long to store large values, as factorials of larger numbers can exceed the limit of standard integer types.

For example, 20! (factorial of 20) is a very large number, but a long long can handle it. However, for numbers greater than 20, even long long might overflow and give incorrect results.

Example Output:

If the user enters 4 for the number of terms, the output will be:

Enter the number of terms in the series: 4
The factorial series up to 4 is:
Factorial of 0 = 1
Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24

This program calculates and prints the factorial for each number from 0 to the user-provided value n. The program uses a for loop to calculate each factorial.

It uses long long to handle large factorials, but there are limitations if the input number gets too large (factorial values grow very fast). For larger values, you may need special libraries like GMP for arbitrary precision.

Best practices in Various Methods to Calculate Factorial Using C Program

Choosing the best method to calculate a factorial depends on factors such as input size, performance, and handling large numbers. For small values, a simple iterative or recursive approach works fine.

Larger values require more advanced techniques like the Gamma function or arbitrary-precision libraries. Always validate inputs and handle edge cases for robustness.

Here are some best practices for implementing factorial calculations in C using various methods:

1. Iterative Method (Using a Loop):

  • Use the smallest possible data type: For smaller values of n, use int. For larger numbers, consider using long long or other larger types.
  • Check for negative input: Factorial is only defined for non-negative integers. Always validate input before proceeding.
  • Optimize loop bounds: Start the loop at 1 and iterate through to n. This avoids unnecessary calculations.

2. Recursive Method:

  • Ensure base case is properly defined: The base case for recursion must stop the function from calling itself indefinitely (e.g., factorial(0) or factorial(1)).
  • Check for negative input: As with the iterative method, factorial is not defined for negative integers.
  • Handle stack overflow risk: Recursion can cause stack overflow for large n. For very large values, an iterative solution might be more efficient.

3. Using tgamma() Function (Gamma Function):

  • Use appropriate type: tgamma() returns a double, so you should cast the result if you need an integer.
  • Be aware of overflow: Even though tgamma() handles large numbers better than regular data types, it still has limitations with very large values.
  • Error handling: Check for negative inputs because the Gamma function isn't defined for negative integers.

4. Handling Large Factorials:

  • Avoid overflow: For very large numbers (e.g., above 20!), consider using arbitrary-precision libraries (like GMP) or larger data types.
  • Avoid recursion with large inputs: Use iterative methods or libraries designed for big integers to avoid stack overflow in recursion.
  • Optimize memory usage: If you're calculating many factorials, store the intermediate results in a memoized array to avoid redundant calculations.

5. General Best Practices:

  • Edge cases: Always handle edge cases like 0!, 1!, and negative inputs.
  • Optimize for performance: When calculating multiple factorials, store previous results to avoid redundant computation (memoization).
  • Modularize: Break down the logic into smaller functions if needed, such as separating input validation from the calculation logic.

Now that you have a good grasp of factorial, it’s time to assess your knowledge with a small test.

How Well Do You Know Factorials in C? 10 MCQs

This quiz will help you gauge your understanding and reinforce key concepts. Let’s see how well you know your C programming fundamentals!

1. What is the factorial of 0 (0!) by definition?

A) 0

B) 1

C) Undefined

D) Depends on input

2. Which of the following loops is most commonly used to calculate factorial in C?

A) for loop

B) while loop

C) do-while loop

D) switch statement

3. What will be the output of the following C program?

#include <stdio.h>
int main() {
int n = 3, result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
printf("%d", result);
return 0;
}

A) 6

B) 3

C) 9

D) 12

4. Which of the following is NOT an approach to computing factorial in C?

A) Iteration using loops

B) Recursion

C) Using tgamma() function

D) Using malloc() function

5. What is the base condition in a recursive function for factorial?

A) if (n == 1) return 1;

B) if (n == 2) return 2;

C) if (n == 0) return 0;

D) No base condition is required

6. What happens if recursion is used to calculate the factorial of a very large number (e.g., 1000!)?

A) It runs successfully

B) It causes a stack overflow error

C) It returns an incorrect result

D) It prints 0

7. What is the correct function prototype for a recursive factorial function in C?

A) int factorial(int n);

B) void factorial();

C) float factorial(int x, int y);

D) int factorial();

8. How can factorial calculation be optimized for repeated calls?

A) Using memoization

B) Using recursion

C) Using while loops

D) Increasing int size

9. Why is long long used for factorial calculations instead of int?

A) It’s faster

B) It supports larger values

C) It requires less memory

D) It prevents recursion errors

10. What is the primary drawback of using the tgamma() function for factorial calculations?

A) It’s inaccurate for large numbers

B) It’s limited to integers

C) It returns a floating-point value

D) It’s slower than loops

Understanding factorial calculations is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.

How Can upGrad Help You Master C Programming?

upGrad’s courses provide in-depth training in C programming, covering fundamental concepts like loops, recursion, functions, and pointers. You’ll gain hands-on experience in writing efficient C programs, including factorial calculations, data structures, and algorithm optimization.

By learning C programming, you’ll build a strong foundation for software development, competitive programming, and system-level programming.

Check out some of these upGrad courses to take your programming skills to the next level!

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!

Similar Reads:

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Addition of Two Numbers in C: A Comprehensive Guide to C Programming

String Anagram Program in C

C Program to check Armstrong Number

Array in C: Introduction, Declaration, Initialisation and More

Exploring Array of Pointers in C: A Beginner's Guide

What is C Function Call Stack: A Complete Tutorial

Discovering C Operators: An Overview with Types and Examples!

Binary Search in C

Conditional Operator in C

Constant Pointer in C: The Fundamentals and Best Practices

Constants in C Explained

Dangling Pointer in C: Causes, Risks, and Prevention Techniques

Find Out About Data Structures in C and How to Use Them?

C Program to Convert Decimal to Binary

FAQs

1. What is the maximum number for which the factorial can be calculated using the long long data type in C?

The long long data type can hold values up to 9223372036854775807. Factorials grow extremely quickly, and values greater than 20! will likely overflow a long long variable. You should be cautious when calculating factorials for numbers larger than 20.

2. How can I handle very large factorials beyond the range of long long?

To handle larger factorials, consider using a big integer library like GMP (GNU Multiple Precision) or implement custom arbitrary-precision arithmetic to calculate and store large factorials.

3. Can I use recursion to calculate the factorial in this program instead of a loop?

Yes, factorials can be calculated using recursion. In the recursive approach, the function calls itself to calculate the factorial. However, for larger numbers, recursion can lead to a stack overflow.

4. How does the performance of the for loop approach compare to recursion for calculating factorials in C?

The for loop approach is generally more efficient and avoids the risk of stack overflow associated with recursion. Recursion involves additional overhead due to function calls, especially for large values of n.

5. What happens if I input a negative number?

Factorial is not defined for negative numbers. The program should either handle this input by displaying an error or by returning a specific message indicating that the factorial of a negative number cannot be calculated.

6. Can I calculate the factorial of a decimal (floating-point) number?

Factorial is only defined for non-negative integers. However, the Gamma function can be used to calculate the "factorial" of non-integer values. If you need to compute such values, you'll need to use a different method (e.g., using tgamma() from the math library).

7. How does the program handle large factorial numbers like 20! and 30!?

The long long data type can handle the factorial of numbers up to 20!, but beyond this, it may result in overflow. For example, 20! is the largest factorial that can be accurately calculated using long long in C. Beyond that, you’ll encounter incorrect results due to overflow.

8. What does the program do when the factorial result exceeds the maximum value of long long?

If the factorial value exceeds the range of long long, it will cause an overflow, leading to incorrect results. The program will display an incorrect factorial value, or the program could crash depending on how the overflow is handled.

9. Can I use double instead of long long for factorial calculations?

While double can hold larger values than long long, it is less precise when dealing with very large numbers. It can lead to loss of precision for large factorials because it can only accurately store numbers up to a certain size.

10. What are some alternative methods to improve the efficiency of calculating factorials in C?

To improve efficiency, you can use methods like memoization (storing already computed factorial values to avoid redundant calculations) or dynamic programming, especially when you need to compute multiple factorials.

11. How can I modify the program to print the factorial for each number up to n without calculating each factorial again?

Instead of calling the factorial function in every iteration of the loop, you can accumulate the factorial by storing the product incrementally. This way, you only multiply once for each number, rather than recalculating the factorial from scratch each time.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.