# C++ Program to Find Factorial of a Number using Dynamic Programming

C++ProgrammingServer Side Programming

The factorial of a positive integer n is equal to 1*2*3*...n. Factorial of a negative number does not exist. Here a C++ program is given to find out the factorial of a given input using dynamic programming.

## Algorithm

Begin
fact(int n):
Initialize
i = 1, result = {0}
result = 1
for i = 1 to n
result[i] = I * result[i-1]
Print result
End

## Example Code

#include <iostream>
using namespace std;
int result = {0};
int fact(int n) {
if (n >= 0) {
result = 1;
for (int i = 1; i <= n; ++i) {
result[i] = i * result[i - 1];
}
return result[n];
}
}
int main() {
int n;
while (1) {
cout<<"Enter integer to compute factorial (enter 0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fact(n)<<endl;
}
return 0;
}

## Output

Enter integer to compute factorial (enter 0 to exit): 2
2
Enter integer to compute factorial (enter 0 to exit): 6
720
Enter integer to compute factorial (enter 0 to exit): 7
5040
Enter integer to compute factorial (enter 0 to exit): 10
3628800
Enter integer to compute factorial (enter 0 to exit): 0