C Program to Find Factorial of a Number Using Recursion

1. Introduction

The Factorial of a non-negative integer n, denoted by n! is the product of all positive integers less than or equal to n. Recursion offers a direct approach to compute factorials. This post presents a C program to calculate the factorial of a number using recursion.

2. Program Overview

The steps of the program are:

1. Define a recursive function to compute the factorial of a given number.

2. Get user input for the desired number.

3. Compute and display the factorial using the recursive function.

3. Code Program

#include <stdio.h>

// Recursive function to find factorial of a number
long long factorial(int n) {
    if (n == 0)  // Base condition
        return 1;
    else
        return n * factorial(n - 1);  // Recursive call
}

int main() {
    int num;

    // Asking user for input
    printf("Enter a non-negative integer: ");
    scanf("%d", &num);

    // Ensuring the entered number is non-negative
    if(num < 0) {
        printf("Please input a non-negative integer.\n");
        return 1;
    }

    // Displaying the factorial
    printf("Factorial of %d = %lld\n", num, factorial(num));

    return 0;
}

Output:

Given the input of 5, the output will be:
Factorial of 5 = 120

4. Step By Step Explanation

1. Recursive Function: The function factorial computes the factorial of an integer.

- When n is 0, it returns 1 (base case).

- For other values of n, it multiplies n with the result of a recursive call for n-1.

2. Main Function: This function initiates by asking the user to provide a non-negative integer.

3. Validation: If the user enters a negative number, the program prompts to input a non-negative integer.

4. Calculation & Output: The factorial is then determined using our recursive function, and the result is presented to the user.

Comments