Factorial Program in C++
Written by
Factorial is the product of all the numbers starting from 1 till the given number.
For example: Factorial of 5 will be = 1*2*3*4*5 = 120
Note: Factorial of a negative number doesn’t exist. And, the factorial of 0 is 1.
Methods:
- Naïve approach
- Using Recursion
Method 1: Naïve approach
Logic:
Factorial of a non-negative integer x is the multiplication of all the integers smaller than or equal to x.
Algorithm:
- Take input of a number from the user.
- Initialize a variable to store the product of the numbers.
- Use a for loop to iterate from 1 to the given number.
- Multiply each number with the fact variable during each iteration.
- Print the final product as the output, which represents the factorial of the given number.
Code:
#include <iostream>
using namespace std;
int main()
{
int n, fact = 1;
cout << "Enter number";
cin >> n;
for (int i = 1; i <= n; i++)
fact = fact * i;
cout << "\n Factorial of given number is:" << fact;
return 0;
}
Output:
Enter number: 6
Factorial of given number is:720
Method 2: Using function
Logic:
The same logic is used as above but here we are using function.
Algorithm:
- Take input of a number from the user.
- Initialize a variable to store the product of the numbers.
- Define a function that takes in 2 parameters: the current product and the current number.
- Use a for loop to iterate from 1 to the given number.
- Within the for loop, call the function and pass in the current product and current number as parameters.
- The function should multiply the current number with the current product.
- Store the returned value in the fact variable.
- Print the final value of the
fact
variable as the output, which represents the factorial of the given number.
Code:
#include <iostream>
using namespace std;
int factorial(int fact, int n)
{
fact = fact * n;
return fact;
}
int main()
{
int n, fact = 1;
cout << "Enter number";
cin >> n;
for (int i = 1; i <= n; i++)
fact = factorial(fact, i);
cout << "\n Factorial of given number is:" << fact;
return 0;
}
Output:
Enter number: 7
Factorial of given number is: 5040