fastread homefastrread library fastread menu

C : Find the Factorial of a Number Using Recursion

Tutorial by:Manisha Dubey      Date: 2016-06-17 03:52:32

❰ Previous Next ❱

Example to find the factorial of a non-negative integer (entered by the user) using recursion.

The factorial of a positive number n is given by:

factorial of n (n!) = 1*2*3*4....n

The factorial of a negative number doesn't exist. And, the factorial of 0 is 1.

 

Example: Factorial of a Number Using Recursion

#include <stdio.h>
long int multiplyNumbers(int n);

int main()
{
    int n;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    printf("Factorial of %d = %ld", n, multiplyNumbers(n));
    return 0;
}
long int multiplyNumbers(int n)
{
    if (n >= 1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
}

Output

Enter a positive integer: 6
Factorial of 6 = 720

 

 
 

Suppose the user entered 6.

Initially, the multiplyNumbers() is called from the main() function with 6 passed as an argument.

Then, 5 is passed to the multiplyNumbers() function from the same function (recursive call). In each recursive call, the value of argument n is decreased by 1.

When the value of n is less than 1, there is no recursive call.

❰ Previous Next ❱


C

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website