Calculate Factorial of a Number in C

Exercise:

Write a C Program to calculate factorial of a number.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    int num, i;
    unsigned long long fact = 1;
    printf("Enter an integer: ");
    scanf("%d", &num);

    // shows error if the user enters a negative integer
    if (num < 0) {
        printf("Error! You entered Negative Number.");
    }
    else {
        for (i = 1; i <= num; ++i) {
            fact *= i;
        }
        printf("Factorial of %d = %llu", num, fact);
    }
    return 0;
}
Click Here to View the Output!
Enter an integer: 3                                            
Factorial of 3 = 6
Click Here to View the Explanation!
  • This program is used to calculate the factorial of a number.
  • The program requests the user to enter a positive integer and stores it in an integer variable num using the scanf() function.
  • A variable fact of the type unsigned long long is initialized as fact = 1 since the factorial of a positive number can be a large value.
  • An if…else is used which checks whether num is a negative number, if true, an error message is displayed. Else, a for loop is used to iterate num number of times and each time multiply i with fact and increment i by one. The result is stored in fact.
  • The factorial of num is printed and displayed on the screen.
  • The return 0 statement is used to exit the program execution.

%d bloggers like this: