To find factorial of a number in C++ Programming a common question in practical exams. Not only in C++, but also in C, Java, VB, C#, Python, etc.
What is factorial of a number?
Factorial of a number is the product of numbers from 1 to that number.
For example:
If we want to find factorial of 5,
Then it should be : 1 x 2 x 3 x 4 x 5 = 120.
Like this factorial of 4 should be 24. ( 1 x 2 x 3 x 4 = 24).
In computer, we use * symbol instead of multiplication symbol (x).
C++ Program to find Factorial of a Number
Here we find factorial of a given number using for loop, which starts from 1 till to given number. Variable ‘fact’ gets multiplication products from 1 to that number.
#include <iostream> using namespace std; int main() { int num, fact = 1; cout << "Type a number : " ; cin>>num; for(int i=1;i<=num;i++) { fact = fact * i; } cout<<"Factorial of " << num << " is : "<< fact; return 0; }
Using While Loop
#include <iostream> using namespace std; int main() { int num, fact = 1, i=1; cout << "Type a number : " ; cin>> num; while(i <= num) { fact = fact * i; i++; } cout<< "Factorial of " << num << " is : "<< fact; return 0; }
Find Factorial using Recursion
Recursion is the calling a function from it’s function body.
Here is a function named factorial and inside it’s body, program call again same function name(factorial) again.
#include <iostream> using namespace std; int factorial(int); int main() { int num; cout << "Type a number : " ; cin>>num; cout<<"Factorial of " << num << " is : "<< factorial(num); return 0; } int factorial(int num) { if(num == 1) return 1; else { return(num * factorial(num-1)); } }
Sample Output:

Be First to Comment