C Example for Beginners: C Program to Find Factorial of a Number Using Recursion

(C programming Example for Beginners)

C Program to Find Factorial of a Number Using Recursion

In this example, you will learn 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.

 


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, multiplyNumbers() is called from main() with 6 passed as an argument.

Then, 5 is passed to multiplyNumbers() 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 and the factorial is returned ultimately to the main() function.

 

C Example for Beginners: C Program to Find Factorial of a Number Using Recursion

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.