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 <stdio.h>
  2. int main() {
  3. int n, i;
  4. unsigned long long fact = 1;
  5. printf("Enter an integer: ");
  6. scanf("%d", &n);
  7. // shows error if the user enters a negative integer
  8. if (n < 0)
  9. printf("Factorial of a negative number doesn't exist.");
  10. else {
  11. for (i = 1; i <= n; ++i) {
  12. fact *= i;
  13. }
  14. printf("Factorial of %d = %llu", n, fact);
  15. }
  16. return 0;
  17. }

Output:

Enter an integer: 7
Factorial of 7 = 5040