Find the Factorial of a Number

The factorial of any number is given by the product of 1 to the number itself.

Fact (n) = 1 * 2 * 3 * … * n-1 * n

Key Points:

  1. Factorial of any negative number doesn’t exists.
  2. Factorial of 0 is 1.
#include <stdio.h>
int main() {
    int n, i;
    int fact = 1;
    printf("Enter a number");
    scanf("%d", &n);
    if (n < 0)
        printf("\n Factorial of a negative number does not exists");
    else {
        for (i = 1; i <= n; ++i) {
            fact *= i;
        }
        printf("Factorial of %d is %d", n, fact);
    }

    return 0;
}

Explaination :

The program takes an integer n as input and checks if is positive. If negative, then display error message. Else, calculate its factorial by a for-loop with iterating from 1 to n. Each time the fact is multiplied with i and updated to perform the factorial.