C Program to Find Factorial of a Number Using Recursion

Created with Sketch.

C Program to Find Factorial of a Number Using Recursion

In this tutorial, we’ll explore how to create a C program to find the factorial of a number using recursion. The factorial of a non-negative integer , denoted by !, is the product of all positive integers up to . The recursive approach provides an elegant solution to compute the factorial. Let’s delve into the details of the algorithm and the C code.

Factorial Calculation Algorithm

  1. Base Case: If is 0 or 1, return 1 (base case for factorial).
  2. Recursive Call: If is greater than 1, recursively call the factorial function with .
  3. Multiply by : Multiply the result obtained from the recursive call by .

C Program for Finding Factorial Using Recursion

#include <stdio.h>

// Function to find factorial using recursion
long long factorial(int n) {
    // Base case
    if (n == 0 || n == 1) {
        return 1;
    } else {
        // Recursive call
        return n * factorial(n - 1);
    }
}

int main() {
    int number;

    // Input from user
    printf("Enter a non-negative integer: ");
    scanf("%d", &number);

    // Check if the input is non-negative
    if (number < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        // Compute and display factorial
        printf("Factorial of %d = %lld\n", number, factorial(number));
    }

    return 0;
}

Output Example

Example 1: Positive Integer

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

Example 2: Zero

 
Enter a non-negative integer: 0
Factorial of 0 = 1

Example 3: Negative Integer

 
Enter a non-negative integer: -3
Factorial is not defined for negative numbers.

Explanation

  1. Factorial Function: The factorial function is defined to calculate the factorial of a given non-negative integer using recursion.
  2. Base Case: The base case checks if the input is 0 or 1, in which case the factorial is 1.
  3. Recursive Call: For input greater than 1, the function recursively calls itself with .
  4. Multiplication: The result obtained from the recursive call is multiplied by .

Conclusion

This C program efficiently computes the factorial of a non-negative integer using a recursive approach. Understanding the recursive nature of the algorithm is crucial for implementing similar recursive solutions in your programs.

Feel free to experiment with different inputs and understand how the recursion unfolds. If you have any questions or need further clarification, don’t hesitate to ask!

Leave a Reply

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