
This simple C Program for factorial is a perfect concept that helps beginners in understanding the concepts of loops and functions in C, as these are some of the must-learn topics for anyone starting out his journey. Whether you're new to coding or polishing your skills, mastering the C Program for factorial will enhance your understanding of iteration and recursion. Read this article and discover how this basic but essential program can build the foundation for more complex tasks.
| C Program For Factorial Using Loops |
| #include <stdio.h> #include<conio.h> // Function to find factorial of given number int main() { int n, i; unsigned long long fact = 1; // Factorial can be a large number, so we use unsigned long long instead of Int. printf("Enter an integer: "); scanf("%d", &n); // Check if the user entered a negative number if (n < 0) printf("Error! Factorial of a negative number doesn't exist."); else { for (i = 1; i <= n; ++i) { fact *= i; // fact = fact * i; } printf("Factorial of %d = %llu", n, fact); } return 0; } |
| Output- Enter an integer: 5 Factorial of 5 = 120 |
| C Program For Factorial Using Recursion |
| #include <stdio.h> #include<conio.h> // Function prototype unsigned long long factorial(int n); int main() { int n; printf("Enter an integer: "); scanf("%d", &n); // Check if the user entered a negative number if (n < 0) printf("Error! Factorial of a negative number doesn't exist."); else printf("Factorial of %d = %llu", n, factorial(n)); return 0; } // Recursive function to find the factorial of a number unsigned long long factorial(int n) { if (n == 0) // Base case return 1; else return n * factorial(n - 1); // Recursive case } |
| Output- Enter an integer: 5 Factorial of 5 = 120 |