+1 vote
in Programming Languages by (74.2k points)
Please give me C code to calculate the factorial of a number using a recursive function.

1 Answer

+2 votes
by (8.9k points)
 
Best answer

Recursion is a programming technique where a function calls itself directly or indirectly. You can use it to calculate the factorial of a number. The factorial of negative number is not defined, so the number should be non-negative i.e. >=0. The factorial of 0 and 1 is 1. 

Here is the code based on recursion.

#include <stdio.h>

int factorial(int n) {

    if (n == 0 || n == 1) {

        return 1;

    } else {

        return n * factorial(n - 1);

    }

}

int main() {

    int num = 10;

    if (num < 0){

        printf("Factorial of a negative number is not defined\n");

    }

    else{

        printf("Factorial of %d is %d\n", num, factorial(num));

    }

    return 0;

}

In the above code, the factorial() function calls itself until n becomes 1.

Related questions


...