Simple C program to calculate the factorial of a given number

This C program calculates the factorial of a given number entered by the user. Factorial of a non-negative integer n is denoted as n! and is the product of all positive integers less than or equal to n.

The program consists of the following steps:

  • The user is prompted to enter a number.
  • The factorial() function is defined to calculate the factorial recursively. It takes an integer parameter n and returns the factorial of n.
  • Inside the factorial() function a base case is defined where the factorial of 0 is 1.
  • For any other value of n, the factorial() function recursively calls itself with the n-1 and multiplies the result by n.
  • In the main() function, user input is stored in the variable num.
  • The factorial() function is called with input number and the result is stored in the variable fact.
  • Finally, calculated factorial is printed to the console.

Here's a simple C program to calculate the factorial of a given number:

#include <stdio.h>

// Function to calculate factorial
int factorial(int n) {
    if (n == 0) {
        return 1;
    }
    // Recursive case: multiply n by the factorial of (n-1)
    else {
        return n * factorial(n - 1);
    }
}
int main() {
    int num;
    // Input number from user
    printf("Enter a number: ");
    scanf("%d", &num);
    // Calculate factorial
    int fact = factorial(num);   
    // Print the factorial
    printf("Factorial of %d is %d\n", num, fact);
    return 0;
}
output
Enter a number: 5
Factorial of 5 is 120

Explanation:

  • The factorial() function calculates the factorial of a given number n recursively.
  • It has a base case when n is 0, where the factorial is 1.
  • For any other value of n, it recursively calls itself with n-1 and multiplies the result by n.
  • In the main() function, the user inputs a number.
  • The factorial() function is called with the input number and the result is stored in fact.
  • Finally, calculated factorial is printed to console.