Factorial Program in C using Recursion
A recursive approach to finding the factorial involves calling the function itself with a reduced problem size. Here's the code:
#include <stdio.h>
unsigned long long factorial(unsigned int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
unsigned int n;
printf("Enter a number: ");
scanf("%u", &n);
printf("Factorial of %u is %llu\n", n, factorial(n));
return 0;
}
You can also try this code with Online C Compiler
Run CodeUsing Tail Recursion
Tail recursion optimizes recursive functions by reducing the amount of memory used. Here's the factorial code with tail recursion:
#include <stdio.h>
unsigned long long factorial_helper(unsigned int n, unsigned long long acc) {
if (n == 0) {
return acc;
} else {
return factorial_helper(n - 1, acc * n);
}
}
unsigned long long factorial(unsigned int n) {
return factorial_helper(n, 1);
}
int main() {
unsigned int n;
printf("Enter a number: ");
scanf("%u", &n);
printf("Factorial of %u is %llu\n", n, factorial(n));
return 0;
}
You can also try this code with Online C Compiler
Run CodeFrequently Asked Questions
What is factorial program in C?
The factorial of a non-negative integer is calculated via a factorial programme written in C. All positive integers up to the specified number are added together to form it. For instance, 120 is the factorial of 5 (5!).
How to write factorial formula in C?
Apply a loop or recursion to create a factorial formula in C. An example of a recursive method is factorial(n) = (n == 0) ? 1 : n * factorial(n - 1). For instance, 120 is the factorial of 5 (5!).
What is the factorial of 100 factorial?
The sum of all positive integers less than or equal to 100 factorial is known as the factorial of 100 factorial. This number is roughly equal to 9.3326215443944e+157, although it cannot be printed out in full due to its size.
Conclusion
Understanding how to calculate factorials using recursion in C is a valuable skill that highlights the elegance and efficiency of recursive functions. By mastering this technique, you enhance your problem-solving toolkit, making it easier to tackle more complex programming challenges. Keep practicing, and you'll see just how powerful recursion can be.
Recommended Reading:
- Decimal to Binary in C
- Ternary Operator in C
- Conditional Operator in C
- Prime Number Program using C
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.