In this program, we will learn how to write to Find Factorial of a Number using the C++ programming language.
What is Factorial of a Number?
Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n.For example: The factorial of 5 is 120.
5! = 5 * 4 * 3 * 2 *1
5! = 120
We will discuss two ways to write code for it.
- Using loop
- Using recursion
Let's discuss these ways one by one
C++ Programming Code to Find Factorial of Number
Using loop
We will use the for loop in this program. The loop will execute until the number provided by the user is reached.
And in the body of the loop fact variable will be multiplied with the current value i.e. value of i variable and store it back to fact variable.
Code:-
#include <iostream>
using namespace std;
int main() {
int num, fact = 1;
cout << "Enter a number: ";
cin >> num;
for(int i=1; i<=num; i++){
fact = fact * i;
}
cout<<"Factorial of " << num << " is " << fact << endl;
return 0;
}
Output:-
Enter a number: 5
Factorial of 5 is 120
Using recursion
Recursion will be used in this program.
If the base condition is found it will return 1 else it will return the product of n and the factorial of n-1.
code:-
#include <iostream>
using namespace std;
int fact(int n) {
if ((n==0)||(n==1))
return 1;
else
return n*fact(n-1);
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout<<"Factorial of " << num << " is " << fact(num) << endl;
return 0;
}
Output:-
Enter a number: 5
Factorial of 5 is 120