C Program to Print Factorial of a Number
Write a C program to find the Factorial of a number
Factorial is a sequence of a number where we multiply by all previous numbers.
factorial of n (n!) = 1 * 2 * 3 * 4....n
Note : 0! = 1 and 1! = 1
Example :
5! = 1 * 2 * 3 * 4 * 5 = 120
Methods we will discuss
- Iterative approach for factorial
- Recursive approach for factorial
Method 1
For an input num
- Initialize fact = 1
- If num < 0 : Print Error as we can’t calculate factorial of a negative number
- Else run a iterative loop in iteration of (i) between [1, num]
- do fact = fact * i
- print the value of fact
C program:-
#include<stdio.h> int main () { int num = 5, fact = 1; // Can't calculate factorial of a negative number if(num < 0) printf("Error"); else { for(int i = 1; i <= num; i++) fact = fact * i; } printf("Fact %d: %d",num, fact); } // Time complexity: O(N) // Space complexity: O(1)
Output:-
Fact 5: 120
Method 2
This method uses the recursive approach, for input num
For an input num
- Call function getFactorial(num)
- Set base case when num== 0 return 1
- Other cases return num * getFactorial(num-1);
C Program
Run
#include<stdio.h> int getFactorial(int num) { if(num == 0) return 1; return num * getFactorial(num-1); } int main () { int num = 7; int fact = getFactorial(num); printf("Fact %d: %d",num, fact); } // Time complexity: O(N) // Space complexity: O(1) // Auxiliary Space complexity (Function call stack): O(N)
Output
Fact 7: 5040
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
- Positive or Negative number: C | C++ | Java | Python
- Even or Odd number: C | C++ | Java | Python
- Sum of First N Natural numbers: C | C++ | Java | Python
- Sum of N natural numbers: C | C++ | Java | Python
- Sum of numbers in a given range: C | C++ | Java | Python
- Greatest of two numbers: C | C++ | Java | Python
- Greatest of the Three numbers: C | C++ | Java | Python
- Leap year or not: C | C++ | Java | Python
- Prime number: C | C++ | Java | Python
- Prime number within a given range: C | C++ | Java | Python
- Sum of digits of a number: C | C++ | Java | Python
- Reverse of a number : C | C++ | Java | Python
- Palindrome number: C | C++ | Java | Python
- Armstrong number : C | C++ | Java | Python
- Armstrong number in a given range : C | C++ | Java | Python
- Fibonacci Series upto nth term : C | C++ | Java | Python
- Find the Nth Term of the Fibonacci Series : C | C++ | Java | Python
- Factorial of a number : C | C++ | Java | Python
- Power of a number : C | C++ | Java | Python
- Factor of a number : C | C++ | Java | Python
- Strong number : C | C++ | Java | Python
- Perfect number : C | C++ | Java | Python
- Automorphic number : C | C++ | Java | Python
- Harshad number : C | C++ | Java | Python
- Abundant number : C| C++ | Java | Python
- Friendly pair : C | C++ | Java | Python
Login/Signup to comment