English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C Program to calculate the factorial of a number using recursion

Comprehensive Collection of C Programming Examples

In this example, you will learn how to find the factorial of a non-negative integer entered by the user using recursion.

To understand this example, you should be familiar with the followingC Programming LanguageTopic:

The factorial of a positive number n is given by the following formula:

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

The factorial of a negative number does not exist. The factorial of 0 is1.

In this example, you will learn how to use recursion to find the factorial of a number. Visit this page to learn howFactorial using loop.

Factorial using recursion

#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
    int n;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    printf("%d factorial = %ld", n, multiplyNumbers(n));
    return 0;
}
long int multiplyNumbers(int n) {
    if (n>=1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
}

Output the result

Enter a positive integer: 6
6 factorial = 720

Suppose the user entered6.

Initially, multipleNumbers() is called from main() and the6as a parameter.

Then, pass5is passed to multipleNumbers() (recursive call). In each recursive call, the value of parameter n is reduced1.

When the value of n is less than1There is no recursive call, and the factorial is finally returned to the main() function.

Comprehensive Collection of C Programming Examples