Skip to content
doubtly

2 answers

Best answer

Answer: factorial(n) returns 1 when n ≤ 1, otherwise n × factorial(n − 1).

Logic: \( 5! = 5 \times 4! = 5 \times 4 \times 3! = \dots = 120 \). The base case n ≤ 1 stops the recursion.

Program:

#include <stdio.h>

long factorial(int n)
{
    if (n <= 1)
        return 1;                    /* base case: 0! = 1! = 1 */
    return n * factorial(n - 1);     /* recursive call */
}

int main()
{
    int n;

    printf("Enter a number: ");
    scanf("%d", &n);

    if (n < 0)
        printf("Factorial of a negative number is not defined\n");
    else
        printf("Factorial of %d = %ld\n", n, factorial(n));

    return 0;
}

Sample output (actual run):

Enter a number: 5
Factorial of 5 = 120
Doubtly · 23 Apr 2022 Report
Was this answer helpful?

A recursive factorial function calls itself with \(n-1\) until it reaches the base case \(0! = 1\) (or \(1! = 1\)), using \(n! = n \times (n-1)!\).

#include <stdio.h>

long fact(int n) {
    if (n == 0 || n == 1)      /* base case */
        return 1;
    return n * fact(n - 1);    /* recursive call */
}

int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n < 0)
        printf("Factorial of a negative number is not defined\n");
    else
        printf("Factorial of %d = %ld\n", n, fact(n));
    return 0;
}

For \(n = 4\) the calls are: fact(4) = 4 * fact(3), fact(3) = 3 * fact(2), fact(2) = 2 * fact(1), and fact(1) returns 1. The results are then multiplied while returning: \(2 \times 1 = 2\), \(3 \times 2 = 6\), \(4 \times 6 = 24\). So the output is Factorial of 4 = 24.

The base case is essential; without it the function would keep calling itself until the stack overflows.

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.