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 finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program allows you to find the length of a linked list, which is the number of nodes present...