A Program to Find Factorial of a Number

In this example, we are giving a program to find the factorial of a number.


Program to find factorial:

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int n, i;
  5. unsigned long long fact = 1;
  6. cout << "Enter an integer: ";
  7. cin >> n;
  8. // shows error if the user enters a negative integer
  9. if (n < 0)
  10. cout << "Factorial of a negative number doesn't exist.";
  11. else {
  12. for (i = 1; i <= n; ++i) {
  13. fact *= i;
  14. }
  15. cout << "Factorial = " << fact;
  16. }
  17. return 0;
  18. }

Output:

Enter an integer: 7
Factorial = 5040