C Program to Calculate Factorial using Recursion

1. Introduction

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. For example, the factorial of 5, written as 5! is 5 × 4 × 3 × 2 × 1 = 120. The factorial function has a special case: the factorial of 0 is defined to be 1. Factorial is commonly used in mathematics and computer science, especially in calculations involving permutations and combinations.

Recursion, a programming technique where a function calls itself, offers an intuitive way to compute factorials. 

In this post, we'll implement a C program to calculate the factorial of a number using recursion.

2. Program Overview

The program flow will be:

1. Prompt the user to enter a non-negative integer.

2. Use a recursive function to compute its factorial.

3. Display the result.

3. Code Program

#include <stdio.h>  // Integrate the Standard I/O library for input and output functions

// Recursive function to calculate factorial
long long factorial(int n) {
    if (n == 0)  // Base case: factorial of 0 is 1
        return 1;
    else
        return n * factorial(n-1);  // Recursive case: n times factorial of (n-1)
}

int main() {  // The main function, where our program begins

    int number;
    printf("Enter a non-negative integer: ");
    scanf("%d", &number);  // Capture the user's input

    if (number < 0) {  // Ensure the entered number is non-negative
        printf("Error! Factorial for negative numbers is not defined.\n");
        return 1;  // End the program with an error code
    }

    printf("Factorial of %d = %lld\n", number, factorial(number));  // Compute and display the factorial

    return 0;  // Indicate the successful execution of the program
}

Output:

Enter a non-negative integer: 5
Factorial of 5 = 120

4. Step By Step Explanation

1. #include <stdio.h>: By including this header file, we gain access to the essential input/output functions.

2. The recursive factorial function:

  • Base Case: Every recursive function needs a base case to halt the recursion. For factorials, the factorial of 0 is defined as 1.
  • Recursive Case: The factorial of (n) is (n) multiplied by the factorial of (n-1\). This calls the factorial function within itself, leading to a recursive pattern until it reaches the base case.

3. int main(): The principal function where the program starts.

4. User input validation: The program ensures that the user doesn't enter a negative number, as factorials for negative numbers are undefined.

5. Computing and displaying the factorial: The main function calls the recursive factorial function and prints the result.

The magic of recursion is that it breaks a complex problem (like finding the factorial of a large number) into simpler instances of the same problem. Each recursive call deals with a slightly smaller number, making the problem more manageable, until the solution becomes trivial (the base case).

Comments