C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Factorial (recursion)

A recursive function is a function which calls itself

C Program: Factorial (recursion)

C

#include <stdio.h>

 

// Function declaration

int factorial(int n);

 

int main() {

    int num, result;

 

    // Input from user

    printf("Enter a positive integer: ");

    scanf("%d", &num);

 

    // Check for invalid input

    if (num < 0) {

        printf("Error: Factorial of a negative number doesn't exist.\n");

    } else {

        result = factorial(num);   // Function call

        printf("Factorial of %d = %d\n", num, result);

    }

 

    return 0;

}

 

// Recursive function definition

int factorial(int n) {

    if (n == 0 || n == 1)

        return 1;               // Base case

    else

        return n * factorial(n - 1);  // Recursive case

}

Output

 
OUTPUT 1 :
Enter a positive integer: 5
Factorial of 5 = 120

OUTPUT 2 :
Enter a positive integer: -3
Error: Factorial of a negative number doesn't exist.

Explanation

  1. Recursion Concept
    • The function calls itself with a smaller value (n - 1) until it reaches the base case (n == 0 or n == 1).
  2. Base Case
    • Prevents infinite recursion and provides the stopping point.
  3. Example for n = 5

          factorial(5)

          = 5 * factorial(4)

          = 5 * 4 * factorial(3)

          = 5 * 4 * 3 * factorial(2)

          = 5 * 4 * 3 * 2 * factorial(1)

          = 5 * 4 * 3 * 2 * 1 = 120