Introduction:

This C program calculates the factorial of a non-negative integer using a recursive function. Factorial, denoted as n!n!n!, is the product of all positive integers up to nnn. This program prompts the user to input a non-negative integer and computes its factorial through repeated recursive calls. Recursion is a powerful technique in programming that simplifies complex problems by breaking them down into smaller, more manageable parts.

#include <stdio.h>

/*
 * Program to calculate the factorial of a number using recursion.
 * This program takes a non-negative integer as input and computes
 * its factorial through a recursive function.
 */

// Recursive function to calculate factorial
long long factorial(int n) {
    // Base case
    if (n == 0 || n == 1) {
        return 1; // 0! and 1! both equal 1
    }
    // Recursive case
    return n * factorial(n - 1);
}

int main() {
    int number;

    printf("Enter a non-negative integer: ");
    scanf("%d", &number); // Read integer input

    if (number < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        long long result = factorial(number);
        printf("Factorial of %d is: %lld\n", number, result);
    }

    return 0;
}

Input/Output Block:

Input:

  • The user is prompted to enter a non-negative integer.

Example Input:

Enter a non-negative integer: 5

Output:

  • The program outputs the factorial of the given integer.

Example Output:

Factorial of 5 is: 120

Conclusion:

The factorial calculation program effectively demonstrates the use of recursion in C to solve problems involving mathematical computations. By implementing a recursive approach, the program showcases how complex problems can be solved through simpler, smaller instances. This not only reinforces the concept of recursion but also highlights its practical application in calculating factorials. Overall, the program serves as an educational tool for understanding recursive algorithms and their implementation in C, emphasizing the importance of careful handling of base cases and input validation.

Leave a Reply

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

Verified by MonsterInsights