# Program to find Factorial 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:

1. Naïve approach
2. 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:

1. Take input.
2. Initialize a variable to store product of numbers.
3. Run a for loop which runs from 1 till the given number.
4. Multiply each number with the fact variable.
5. Print the output.

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:

1. Take input.
2. Initialize a variable to store product of numbers.
3. Run a for loop which runs from 1 till the given number.
4. Call the function with fact and number as a parameter.
5. Store the returned value in fact variable.
6. Print the output.

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``````

Report Error/ Suggestion

Related Posts:

CopyRight © 2019

CopyRight © 2019