Factorial Program using for Loop
In this method, we use a loop that runs (n – 1) times to get the product of all numbers starting from 1 to n. The below C program use for loop to find the factorial.
C
// C program to implement the above approach #include <stdio.h> // Function to find factorial of given number unsigned int factorial(unsigned int n) { int result = 1, i; // loop from 2 to n to get the factorial for (i = 2; i <= n; i++) { result *= i; } return result; } // Driver code int main() { int num = 5; printf ( "Factorial of %d is %d" , num, factorial(num)); return 0; } |
Output
Factorial of 5 is 120
Time Complexity: O(n)
Auxiliary Space: O(1)
Factorial Program in C
A factorial is the product of all the natural numbers less than or equal to the given number n. For Example, the factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720. In this article, we will explore a few programs to find the factorial of a number in C.
We can write the factorial program in C using two methods:
- Using Loops
- Using Recursion
Contact Us