C Program to Find the Factorial of a Number

This program calculates the factorial of a given number using recursion.

Problem statement

Given a positive integer, we need to calculate its factorial.

C Program to Find the Factorial of a Number

#include <stdio.h>

int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    else
        return n * factorial(n - 1);
}

int main() {
    int number;
    
    printf("Factorial Calculator\n");
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    
    if (number < 0)
        printf("Factorial is not defined for negative numbers.\n");
    else {
        int result = factorial(number);
        printf("The factorial of %d is %d.\n", number, result);
    }
    
    return 0;
}

How it works?

  1. The program includes the necessary header file stdio.h for input/output operations.
  2. The factorial function is defined, which takes an integer n as an argument and returns the factorial of n.
  3. In the main function:
    • A variable number is declared to store the user input.
    • The user is prompted to enter a positive integer.
    • The entered value is stored in the number variable using scanf.
    • If the entered number is negative, a message is displayed stating that factorial is not defined for negative numbers.
    • Otherwise, the factorial function is called with the number as an argument and the result is stored in the result variable.
    • The result is printed using printf.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...