For working professionals
For fresh graduates
More
Explore C Tutorials: From Begi…
1. Introduction to C Tutorial
2. Addition of Two Numbers in C
3. Anagram Program in C
4. Armstrong Number in C
5. Array in C
6. Array of Pointers in C
7. Array of Structure in C
8. C Program to Find ASCII Value of a Character
9. Assignment Operator in C
10. Binary Search in C
11. Binary to Decimal in C
12. Bitwise Operators in C
13. Boolean in C
14. C Compiler for Mac
15. C Compiler for Windows
16. C Function Call Stack
17. C Language Download
18. Operators in C
19. C/C++ Preprocessors
20. C Program for Bubble Sort
21. C Program for Factorial
Now Reading
22. C Program for Prime Numbers
23. C Program for String Palindrome
24. C Program to Reverse a Number
25. Reverse a String in C
26. C string declaration
27. String Input Output Functions in C
28. Calculator Program in C
29. Call by Value and Call by Reference in C
30. Ceil Function in C
31. Coding Vs. Programming
32. Command Line Arguments in C/C++
33. Comments in C
34. Compilation process in C
35. Conditional Statements in C
36. Conditional operator in the C
37. Constant Pointer in C
38. Constants in C
39. Dangling Pointer in C
40. Data Structures in C
41. Data Types in C
42. Debugging C Program
43. Convert Decimal to Binary in C
44. Define And include in C
45. Difference Between Arguments And Parameters
46. Difference Between Compiler and Interpreter
47. Difference Between If Else and Switch
48. Do While Loop In C
49. Double In C
50. Dynamic Array in C
51. Dynamic Memory Allocation in C
52. Enumeration (or enum) in C
53. Evaluation of Arithmetic Expression
54. Factorial of A Number in C
55. Features of C Language
56. Fibonacci Series Program in C Using Recursion
57. File Handling in C
58. For Loop in C
59. Format Specifiers in C
60. Functions in C
61. Function Pointer in C
62. goto statement in C
63. C Hello World Program
64. Header Files in C
65. Heap Sort in C Program
66. Hello World Program in C
67. History of C Language
68. How to compile a C program in Linux
69. How to Find a Leap Year Using C Programming
70. Identifiers in C
71. If Else Statement in C
72. If Statement in C
73. Implementation of Queue Using Linked List
74. Increment and decrement operators in c
75. Input and Output Functions in C
76. How To Install C Language In Mac
77. Jump Statements in C
78. Lcm of Two Numbers in C
79. Length of an Array in C
80. Library Function in C
81. Linked list in C
82. Logical Operators in C
83. Macros in C
84. Matrix multiplication in C
85. Nested if else statement in C
86. Nested Loop in C
87. One Dimensional Array in C
88. Operator Precedence and Associativity in C
89. Overflow And Underflow in C
90. Palindrome Program in C
91. Pattern Programs in C
92. Pointer to Pointer in C
93. Pointers in C: A Comprehensive Tutorial
94. Pre-increment And Post-increment
95. Prime Number Program in C
96. Program for Linear Search in C
97. Pseudo-Code In C
98. Random Access Files in C
99. Random Number Generator in C
100. Recursion in C
101. Relational Operators in C
102. Simple interest program in C
103. Square Root in C
104. Stack in C
105. Stack Using Linked List in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
112. String Comparison in C
113. String Functions in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
118. Structure of C Program
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
122. Toupper Function in C
123. Transpose of a Matrix in C
124. Two Dimensional Array in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
129. User Defined Functions in C
130. What is Variables in C
131. Is C language case sensitive
132. Fibonacci Series in C
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!
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.
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.
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:
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.
Output:
The factorial of 5 is 120
Also Read: String Functions in C
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.
Output:
The factorial of 5 is 120
Also Read: Command Line Arguments in C Explained
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.
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:
Output:
The factorial of 5 is 120
Also Read: What Are Storage Classes in C?
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;
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?
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
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
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]
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:
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.
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):
2. Recursive Method:
3. Using tgamma() Function (Gamma Function):
4. Handling Large Factorials:
5. General Best Practices:
Now that you have a good grasp of factorial, it’s time to assess your knowledge with a small test.
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.
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
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!
Constant Pointer in C: The Fundamentals and Best Practices
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
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.